[英]ggplot2 bar chart labels and colours
I'm having an issue with adding labels and colours to a bar chart using geom_text. 我在使用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. 我也希望比例显示为* 100。 So 77.0%, rather than 0.77
所以是77.0%,而不是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()
To fix the text dodging, drop the group
aesthetic and adjust the dodge amount. 要修复文本闪避,请降低
group
美感并调整闪避量。 To set the fill palette, add a scale_fill_*
call, eg 要设置填充调色板,请添加
scale_fill_*
调用,例如
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.