Vasily A
Vasily A

Reputation: 8646

Error bars are rendered incorrectly when ymax exceeds Y axis scale

I wanted to "crop" my Y axis by using limits in scale_y_continuous:

df1 <- data.frame(xx=c('a','b','c'),
                  yy=c(7, 10, 8),
                  se=c(2, 4, 2))
p <- ggplot(data=df1, mapping = aes(x=xx, y=yy)) + 
  geom_bar(data = df1, position=position_dodge(), stat="identity") +
  geom_errorbar(aes(ymin=yy-se, ymax=yy+se), width=0.1, position=position_dodge())

p # left plot

p + scale_y_continuous(limits=c(0,11)) # middle plot
# Warning message:
# Removed 4 rows containing missing values (geom_path).

In this case one error bar exceeds upper limit of the Y axes, and I would like it to be just cropped (like plot on the right) but in fact the vertical line of error bar is just not rendered at all (cf. plot in the middle). Is there any way to overcome this, besides drawing error bars manually?

left - plot without rescaling, middle - plot with rescaling, error bar is impaired, right - desired plot with "cropped" error bar

Upvotes: 1

Views: 1531

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226532

I believe that

library("scales")
p + scale_y_continuous(limits=c(0,11),oob=squish)

will do it (not tested); "oob" stands for "out of bounds"

The more standard answer is to use

coord_cartesian(ylim=c(0,11))

but that will also change the tick spacing etc.

Upvotes: 1

Related Questions