[英]How to make a stacked bar chart by years with percent values? R ggplot
Here my Data这是我的数据
print(data)
A tibble: 12 x 3
`Age Group` Percent Year
<chr> <dbl> <dbl>
1 Adults 0.78 2017
2 Youth 0.05 2017
3 Children 0.17 2017
4 Adults 0.76 2018
5 Youth 0.07 2018
6 Children 0.17 2018
7 Adults 0.77 2019
8 Youth 0.05 2019
9 Children 0.18 2019
10 Adults 0.06 2020
11 Youth 0.76 2020
12 Children 0.17 2020
My goal is to make a stacked bar chart for each year, but I would like to have labels with the values but in the percentage format (ie 70%).我的目标是为每年制作一个堆积条形图,但我希望有带有值的标签,但采用百分比格式(即 70%)。
What do i need to do?我需要做什么?
We can use the scales::percent
我们可以使用scales::percent
library(ggplot2)
ggplot(df1, aes(Year, y = Percent, fill = `Age Group`)) +
geom_col() +
geom_text(aes(label = scales::percent(Percent)),
position = position_stack(vjust = 0.5)) +
scale_y_continuous(labels = scales::percent_format())
df1 <- structure(list(`Age Group` = c("Adults", "Youth", "Children",
"Adults", "Youth", "Children", "Adults", "Youth", "Children",
"Adults", "Youth", "Children"), Percent = c(0.78, 0.05, 0.17,
0.76, 0.07, 0.17, 0.77, 0.05, 0.18, 0.06, 0.76, 0.17), Year = c(2017L,
2017L, 2017L, 2018L, 2018L, 2018L, 2019L, 2019L, 2019L, 2020L,
2020L, 2020L)), class = "data.frame", row.names = c("1", "2",
"3", "4", "5", "6", "7", "8", "9", "10", "11", "12"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.