Reputation: 273
I would like to make all of my value labels to be at the same height above the bars on ggplot2. How can I do this?
p <- ggplot(figure_df, aes(x=event_type, y=fraction)) +
geom_bar(aes(fill=factor(method)), position=position_dodge(width=0.9), stat="identity") +
facet_grid(~event_time, switch="x") +
theme(axis.text.x = element_text(angle = 45,hjust = 1)) +
geom_text(aes(label=ifelse(method == 'THRIVE',round(pval, 2)," ")))
Upvotes: 1
Views: 983
Reputation: 18754
It's always best to make your questions reproducible. Check it out: making R reproducible questions.
In lieu of the data I don't have, I made some to answer your question. To set a position at the same height for all labels, you can set y
in geom_text
to a static number.
Here's an example:
set.seed(3523)
df1 = data.frame(coloring = rep(LETTERS[1:2], 4),
x = rep(LETTERS[1:4], each = 2),
y = runif(8, 10, 29))
ggplot(df1, aes(x = x, y = y, fill = coloring)) +
geom_col(position = position_dodge(.9)) +
geom_text(aes(y = 10, label = round(y, 1)),
position = position_dodge(.9))
You said you wanted the values above the bars. You can set it to a known value or you can use the data to set a singular static value, like this:
ggplot(df1, aes(x = x, y = y, fill = coloring)) +
geom_col(position = position_dodge(.9)) +
geom_text(aes(y = max(y) + 1, label = round(y, 1)),
position = position_dodge(.9))
If you didn't want them at the same height, but you wanted them at the same distance from the bars, you can do that in a variety of different ways. Here is one method.
ggplot(df1, aes(x = x, y = y, fill = coloring)) +
geom_col(position = position_dodge(.9)) +
geom_text(aes(y = y + 1, label = round(y, 1)),
position = position_dodge(.9))
Upvotes: 4