61

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
  • 559
  • 1
  • 10
  • 26
susjoh
  • 2,298
  • 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

2 Answers2

98

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
  • 67,191
  • 22
  • 172
  • 153
  • 3
    If this is what you wanted, consider accepting this as the correct answer by ticking the check under the vote score on the left of the answer. – Roman Luštrik May 09 '11 at 12:46
0

If someone is trying to accomplish the same zoom effect for a flipped bar chart, the accepted answer won't work (even though the answer is perfect for the example in the question).

The solution for the flipped bar chart is using the argument ylim of the coord_flip function. I decided to post this answer because my bars were also "disappearing" as in the original question while I was trying to re-scale with other methods, but in my case the chart was a flipped one. This may probably help other people with the same issue.

This is the adapted code, based on the example of the question:

ggplot(carrots,aes(y=Mean,x=Farm)) +
  geom_col(fill="slateblue") +
  geom_errorbar(aes(ymin=Mean-SE,ymax=Mean+SE), width=0) +
  coord_flip(ylim=c(200,300)) 

Flipped chart example

Waldi
  • 39,242
  • 6
  • 30
  • 78
  • one should not have more than one `coord_` layer anyways. If you have added coord_flip to a coord_cartesian call, this clearly can mess things up. Regardless, the "modern" way to flip the coordinates is via switch of the x and y aesthetic, here `aes(x = Mean, y = Farm)`. Then, you of course need to specify `xlim = ...` – tjebo Jun 13 '22 at 10:25