Reputation: 156
I'm plotting the modelled population density of several bird species +/- standard error. Because the y variable is density, values of less than zero make no sense, I want to truncate the error bars so they don't go below zero. However, I'm having trouble doing this.
This code works fine, but as you can see for Black Kite the error bars go below zero:
bird.plot.data <- data.frame(species = rep(c("Black kite", "Cormorant","Goosander"),2),
Restored = c(rep("YES",3), rep("NO",3)),
est.count = c(1.48, 3.12, 20.0, 0, 5.18, 2.11),
std.err = c(1.78, 1.78, 1.39, 0, 0.66, 1.02))
bird.plot <- ggplot(data = bird.plot.data, aes(x = Restored))+
facet_wrap(~ species, scales = "free_y")+
geom_col(aes(y = est.count, fill = Restored), position = position_dodge())+
geom_errorbar(aes(ymax = est.count + std.err, ymin = est.count - std.err ))+
scale_fill_manual(values = c("darkgreen", "olivedrab1"))+
theme(axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
axis.title.x = element_blank())+
ylab("Estimated density (birds/km\U00B2)")
last_plot()
I've tried a couple of options. The most obvious one would be to modify the ymin of the error bars themselves to be no lower than zero. However, this messes up the error bars completely and I'm not sure why:
b.p.mod <- ggplot(data = bird.plot.data, aes(x = Restored))+
facet_wrap(~ species, scales = "free_y")+
geom_col(aes(y = est.count, fill = Restored), position = position_dodge())+
geom_errorbar(aes(ymax = est.count + std.err, ymin = max(est.count - std.err, 0)))+
scale_fill_manual(values = c("darkgreen", "olivedrab1"))+
theme(axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
axis.title.x = element_blank())+
ylab("Estimated density (birds/km\U00B2)")
last_plot()
Another option would be to limit the y axis to 0 so the error bar is not shown below zero. However, the cropping method
b.p.mod2 <- bird.plot + ylim(0,NA)
last_plot()
removes the error bar completely, which I don't want. The zooming method
b.p.mod3 <- bird.plot + coord_cartesian(ylim = c(0,NA))
last_plot() # Produces error
Doesn't let me leave the upper end unspecified, which is important as different species have very different densities.
Thoughts? My preferred solution would be to work out why the first option is creating such odd results.
Upvotes: 4
Views: 8276
Reputation: 111
I know this is an old post but maybe somebody will stumble upon the same problem.
For me:
geom_errorbar(aes(ymax = est.count + std.err, ymin = ifelse(est.count - std.err < 0, 0, est.count - std.err)))
works perfectly fine :)
Upvotes: 5