![](/img/trans.png)
[英]How do I create a stacked bar chart in R, where the y axis should denote the percentages for the bars?
[英]How do I create a frequency stacked bar chart however have percentage labels on the bars and frequencies on the y axis, in R?
我从下面的代码开始,但是它没有显示正确的输出。 我想要一个正常的频率堆积条形图来显示条形图上的百分比,但显示 y 轴上的频率。 任何人都可以提供任何建议吗?
ggplot(data = df, mapping = aes(x = Family_Size, y = Freq, fill = Survived)) + geom_bar(stat = "identity") + geom_text(aes(label = paste0(df$Percentage),y=Percentage),size = 3) + theme(plot.title = element_text(hjust = 0.5))
<table><tbody><tr><th>Survived</th><th>Family_Size</th><th>Frequency</th><th>Percentage</th></tr><tr><td>Yes</td><td>1</td><td>20</td><td>20%</td></tr><tr><td>No</td><td>1</td><td>80</td><td>80%</td></tr><tr><td>Yes</td><td>2</td><td>40</td><td>40%</td></tr><tr><td>No</td><td>2</td><td>60</td><td>60%</td></tr></tbody></table>
你在寻找这样的东西吗?
ggplot(df, aes(x = Family_Size, y = Frequency, fill = Survived))+
geom_col()+
scale_y_continuous(breaks = seq(0,100, by = 20))+
geom_text(aes(label = Percentage), position = position_stack(0.5))
编辑:用两位小数格式化百分比
ggplot(df, aes(x = Family_Size, y = Frequency, fill = Survived))+
geom_col()+
scale_y_continuous(breaks = seq(0,100, by = 20))+
geom_text(aes(label = paste(format(round(Frequency,2),nsmall = 2),"%")), position = position_stack(0.5))
可重现的例子
structure(list(Survived = c("Yes", "No", "Yes", "No"), Family_Size = c(1L,
1L, 2L, 2L), Frequency = c(20L, 80L, 40L, 60L), Percentage = c("20%",
"80%", "40%", "60%")), row.names = c(NA, -4L), class = c("data.table",
"data.frame"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.