59

I am trying to create a barplot using ggplot2, with the y axis starting at a value greater than zero.

Lets say I have the means and standard errors for hypothetical dataset about carrot length at three different farms:

carrots<-NULL
carrots$Mean<-c(270,250,240)
carrots$SE<-c(3,4,5)
carrots$Farm<-c("Plains","Hill","Valley")
carrots<-data.frame(carrots)

I create a basic plot:

p<-ggplot(carrots,aes(y=Mean,x=Farm)) +
   geom_bar(fill="slateblue") +
   geom_errorbar(aes(ymin=Mean-SE,ymax=Mean+SE), width=0)
p

This is nice, but as the scale runs from 0 to it is difficult to see the differences in length. Therefore, I would like to rescale the y axis to something like c(200,300). However, when I try to do this with:

p+scale_y_continuous('Length (mm)', limit=c(200,300))

The bars disappear, although the error bars remain.

My question is: is it possible to plot a barplot with this adjusted axis using ggplot2?

Thank you for any help or suggestions you can offer.

agamesh
  • 549
  • 1
  • 10
  • 26
susjoh
  • 2,230
  • 5
  • 20
  • 20
  • 8
    [Beware of dynamite!](http://biostat.mc.vanderbilt.edu/twiki/pub/Main/TatsukiRcode/Poster3.pdf) (pdf) – hadley May 09 '11 at 23:28
  • see http://stackoverflow.com/questions/10365167/geom-bar-bars-not-displaying-when-specifying-ylim for more detailed discussions – Jerry T May 08 '17 at 20:20
  • Does this answer your question? [geom\_bar bars not displaying when specifying ylim](https://stackoverflow.com/questions/10365167/geom-bar-bars-not-displaying-when-specifying-ylim) – tjebo Nov 10 '21 at 07:40

1 Answers1

95

Try this

p + coord_cartesian(ylim=c(200,300))

Setting the limits on the coordinate system performs a visual zoom; the data is unchanged, and we just view a small portion of the original plot.

barplot example

rcs
  • 64,778
  • 22
  • 167
  • 150