Andrew Taylor
Andrew Taylor

Reputation: 3488

ggplot2: line connecting axis to point

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?

Upvotes: 6

Views: 5434

Answers (1)

tonytonov
tonytonov

Reputation: 25608

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

Upvotes: 6

Related Questions