agenis agenis - 2 months ago 12
R Question

add segments to barchart (discrete x-axis) in ggplot2

I am trying to draw segments over each bar of a barchart with

ggplot2
. I know how to do this with a continuous X-axis, but not with this discrete axis.
What I did is a kind of "hack" by making-up a line with text.

It looks nice in the picture, but I don't get the legend for the "limit" metal concentration and, most of all, the length of the segment changes every time I zoom in or out.

Does anyone know which geometry could implement this better?
enter image description here

df = data.frame('metal'=c("Cu", "Fr", "Zn"), 'observed'=c(550, 60, 100), 'limit'=c(200, 150, 120))
ggplot(data=df) + aes(x=metal) +
geom_bar(aes(y=observed), stat="identity", fill="grey") +
geom_text(aes(y=limit, label="_____________"), size=rel(6), color="red")


EDIT:

I just realized it's almost a duplicate of this

Answer

Adapted from this answer

ggplot(data=df) + aes(x=metal) + 
  geom_bar(aes(y=observed), stat="identity", fill="grey") +
  geom_errorbar(aes(y=limit,ymin=limit,ymax=limit,colour="limit"))

enter image description here

Comments