如何创建频率堆积条形图,但在条形图上有百分比标签,在 y 轴上有频率,在 R 中?

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"))