I am in a new field where they put letters directly on top of error bars to denote significance. I am able to put labels on top of my error bars, but they are uniformly spaced away from the bars, leaving some with small errors very far away from the bars and looking very strange. Is there a way to put the letter right on top of the error bar? In other words, can I adjust each individual label for each bar?
Here is my code:
my_lab<-c("A","B","BC","C","C","BC")
ggplot(g, aes(x=factor(rate, level=c('0','0.1','1.8','7.3','10.3','15.3')), y=number, fill=species))
geom_bar(stat='identity', color="black", width = 0.5)
geom_errorbar(aes(ymax=number se, ymin=number), width=0.2)
labs(y=my_y_title, x=expression("Ethanol release rate (g/day)"))
geom_text(data=g, aes(label=my_lab), size=8, vjust=-23)
theme(panel.grid.major = ele[enter image description here][1]ment_blank(),
panel.grid.minor = element_blank(),panel.background = element_blank(),
axis.line = element_line(colour = "black"))
theme(text = element_text(size=20))
theme(axis.text.x = element_text(vjust = 0.95, hjust=1))
theme(axis.text.y = element_text(hjust=1))
theme(legend.position = "none")
scale_fill_manual(values=c('#104E8BC8'))
theme(plot.title = element_text(vjust = -12, hjust = 0.7))
theme(plot.subtitle = element_text(vjust = -12, hjust = 0.7))
theme(plot.margin = margin(t = 0, # Top margin
r = 0, # Right margin
b = 0, # Bottom margin
l = 0))```
CodePudding user response:
You can just define aes(y = number se, ...)
in the text layer to place the text at the top position of the bar.
You can set vjust = 0
to have the text touch the errorbar, or make it smaller (e.g. vjust = -0.5
) to move it slightly away from the top of the bar. Note that the vjust
is in units of text height, so vjust = -0.5
moves the text half a text height above the anchor point.
Alternatively, you can use the nudge_y
argument to move the text by units defined by the data.
Dummy example with build-in dataset below:
library(dplyr)
library(ggplot2)
df <- iris |>
group_by(Species) |>
summarise(number = mean(Sepal.Width), se = sd(Sepal.Width) / sqrt(n())) |>
mutate(label = c("A","BC", "DEF"))
ggplot(df, aes(Species, number))
geom_col()
geom_errorbar(
aes(ymin = number, ymax = number se),
width = 0.2
)
geom_text(
aes(y = number se, label = label),
vjust = 0, nudge_y = 0
)
Created on 2022-10-11 by the reprex package (v2.0.1)