Reputation: 493
I'm having an issue with adding labels and colours to a bar chart using geom_text.
Here's an eg of the data: Data
Season Answer n freq
Spring Yes 103 0.77
Spring No 30 0.23
Winter Yes 75 0.85
Winter No 13 0.15
For labels
The labels bunch up together, rather than there being a figure at the end of each bar.
ggplot(data = a, aes(x = Answer, y = freq)) +
geom_bar(aes(fill = season),stat = "identity", position = "dodge") +
theme_minimal() +
scale_y_continuous(labels = scales::percent, limits = c(0, 1)) +
geom_text(aes(label = freq, group = Answer),
position=position_dodge(width = 0.5), vjust = -1.5) +
ggtitle(label = "x") +
labs (x = "%") +
coord_flip()
I would like there to be a proportion at the end of each bar, rather than them overlapping on each other.
I would also like the proportions to show as *100. So 77.0%, rather than 0.77
For colours
I would like to amend the colours from the standard blue and red here as well. When I add a palette with four colours each bar gets an individual colour , rather than one for 'spring' and one for 'winter'. You'll see that doing this also messes up all the labels and the legend.
If I use a colour palette with two colours I get this:
Error: Aesthetics must be either length 1 or the same as the data (4): fill, x, y
ggplot(data = a, aes(x = Answer, y = freq)) +
geom_bar(aes(fill = "palette"),stat = "identity", position = "dodge") +
theme_minimal() +
scale_y_continuous(labels=scales::percent,limits= c(0, 1))+
geom_text(aes(label = freq, group = Answer),
position = position_dodge(width = 0.5),
vjust = -1.5) +
ggtitle(label = "x") +
labs (x = "%") +
coord_flip()
Upvotes: 1
Views: 3730
Reputation: 43334
To fix the text dodging, drop the group
aesthetic and adjust the dodge amount. To set the fill palette, add a scale_fill_*
call, e.g.
library(ggplot2)
a <- data.frame(Season = c("Spring", "Spring", "Winter", "Winter"),
Answer = c("Yes", "No", "Yes", "No"),
n = c(103L, 30L, 75L, 13L),
freq = c(0.77, 0.23, 0.85, 0.15), stringsAsFactors = FALSE)
ggplot(data = a, aes(x = Answer, y = freq, fill = Season, label = scales::percent(freq))) +
geom_col(position = "dodge") +
geom_text(position = position_dodge(width = .9)) +
scale_y_continuous(labels = scales::percent, limits = c(0, 1)) +
scale_fill_brewer(type = 'qual') +
theme_minimal() +
labs(title = "x", x = "%") +
coord_flip()
Upvotes: 1