Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: line connecting axis to point

Tags:

r

ggplot2

data:

df<-data.frame(grp=letters[1:4],perc=runif(4))

First option:

First, create a second dataset that contains zeros for each group

df2<-rbind(df,data.frame(grp=df[,1],perc=c(0,0,0,0)))

Then plot with geom_points and geom_line:

ggplot(df,aes(y=perc,x=grp))+
  geom_point()+
  geom_line(data=df2, aes(y=perc, x=grp))+
  coord_flip()

TooMuchWork_LooksGood

Which looks just fine. Just too much extra work to create a second dataset.

The other option is using geom_bar and making the width tiny:

ggplot(df,aes(y=perc,x=grp))+
  geom_point()+
  geom_bar(stat="identity",width=.01)+
  coord_flip()

WeirdThinBars_NotSameSizeinPDF

But this is also weird, and when I save to .pdf, not all of the bars are the same width.

There clearly has to be an easier way to do this, any suggestions?

like image 360
Andrew Taylor Avatar asked Mar 27 '15 13:03

Andrew Taylor


1 Answers

Use geom_segment with fixed yend = 0. You'll also need expand_limits to adjust the plotting area:

ggplot(df, aes(y=perc, x=grp)) +
    geom_point() +
    geom_segment(aes(xend=grp), yend=0) +
    expand_limits(y=0) +
    coord_flip()

enter image description here

like image 157
tonytonov Avatar answered Oct 22 '22 11:10

tonytonov