R中仅一个变量的堆积条形图(带有百分比)?

时间:2019-07-29 13:19:27

标签: r ggplot2 plot bar-chart

我正在尝试为数据中的每个人制作一个仅一个变量(选项)的堆叠条形图,其中y轴是百分比(因此范围是0到100%)。

   id option
 1   1  1
 2   2  1
 3   2  2
 4   3  3
 5   4  4
 6   5  5
 7   6  1
 8   6  5
 9   6  6
 10  7  2
 11  7  3
 12  8  3
 13  8  5
 14  8  6
 15  9  2
 16 10  1 

我尝试了以下代码,但无法获得想要的内容

 ggplot(df, aes(x = '' ,y = option, fill = option)) +
 geom_bar(position = "fill", stat = 'identity') +
  scale_y_continuous(labels = scales::percent)

我想要这样的东西,但是只有一个带有6种不同颜色的条(因为option变量有6个选项)。任何帮助,将不胜感激!!

enter image description here

1 个答案:

答案 0 :(得分:0)

首先,您需要将选项更改为因子df$option <- as.factor(df$option)

然后ggplot(df, aes(x='', fill=option)) + geom_bar(position = "fill"),这就是结果。

Stacked proportional plot