I am creating a point plot and I wanted to add a bar to the bottom of a point plot. I can't seem to find out how to do this in the ggplot documentation. I was hoping to add at bar the spanned the entire x-axis with a set y-axis value. Here is an example of the data I am working with
d=data.frame(drink=c("coffee","tea","water"), mean=c(5,6,9), lower=c(4.5,5.6,8.7), upper=c(5.5,6.3,9.5))
and here is the code I am using
ggplot()
geom_errorbar(data=d, mapping=aes(x=drink, ymin=upper, ymax=lower), width=0.2, size=1, color="blue")
geom_point(data=d, mapping=aes(x=drink, y=mean), size=4, shape=21, fill="white")
scale_y_continuous(n.breaks = 10) ylim(0, 12)
Here is what the plot currently looks like
and this is what I want to add
CodePudding user response:
The annotate()
function allows you to directly specify a layer without intermediate data.frame. In ggplot2, the -Inf
/Inf
values for continuous variables indicate to place something at the extremes.
library(ggplot2)
d=data.frame(drink=c("coffee","tea","water"),
mean=c(5,6,9),
lower=c(4.5,5.6,8.7),
upper=c(5.5,6.3,9.5))
ggplot(d)
geom_errorbar(
mapping=aes(x=drink, ymin=upper, ymax=lower),
width=0.2, size=1, color="blue")
geom_point(
mapping=aes(x=drink, y=mean),
size=4, shape=21, fill="white")
scale_y_continuous(n.breaks = 10, limits = c(0, 12))
annotate("rect", xmin = -Inf, xmax = Inf,
ymin = -Inf, ymax = 1, fill = "black")
Created on 2021-09-13 by the reprex package (v2.0.1)