条形图百分比子组

时间:2020-02-09 18:17:02

标签: r

我有一个来自csv的包含15个指标(列)的数据集。 1个指标称为Cancer

这是数据集中的列的样子

Cancer:  yes no yes no

我只想有一张条形图(堆积的和正常的),显示癌症的是和否百分比

2 个答案:

答案 0 :(得分:0)

1。创建minimal reproducible example

df <- data.frame(Cancer = c("yes", "yes", rep("no", 8)))

2。使用ggplot2scales的解决方案

如果只需要绘图摘要,我们可以直接使用ggplot:

library(ggplot2)
library(scales)
ggplot(df, aes(x = Cancer)) +  
  geom_bar(aes(y = (..count..)/sum(..count..))) + 
  scale_y_continuous(labels=scales::percent) +
  labs(x="Cancer", y="Relative frequency [%]")

enter image description here

答案 1 :(得分:0)

这应该使用ggplot2进行所需的堆积图。

library(ggplot2)

ggplot(df,aes(x="", fill = Cancer))+
  #Do the bar plot scaled to 1
  geom_bar(position = "fill") +
  #Change the y axis labels as percent
  scale_y_continuous(labels = scales::percent)

stacked plot

相关问题