【问题标题】:How do I plot a stacked bar chart, given percentages?给定百分比,如何绘制堆积条形图?
【发布时间】:2020-03-11 17:03:05
【问题描述】:

如何使用 ggplot2 绘制堆积条形图?

鉴于以下数据,我希望 x 轴为年份,y 轴被视为堆叠,late_percent 为比例。

我希望 y 轴根据给定的百分比填充 2 种颜色:0.16 表示 16% 一种颜色,84% 表示另一种颜色;每年都采用同样的方法。

这是我的数据框:

   year   percent
1: 2015   0.16
2: 2016   0.23
3: 2017   0.14
4: 2018   0.64
5: 2019   0.15
6: 2020   0.24

我试过了:

ggplot(data = mydata)+
geom_bar(aes(x = year, y = percent),position = 'fill', stat = 'identity')

【问题讨论】:

  • 您可以向我们展示您到目前为止所尝试的内容。
  • 把填入aes()然后使用position = position_stack()
  • 堆叠了哪些值?在 x 轴值 year = 2015 处,您有一个 ypercent = 0.16。堆积条形图需要 2 个或更多 y 值来表示单个 x 值,通常通过 fill 颜色映射来区分。你所有的年份都有一个 y 值,所以没有什么可以叠加的。如果有更多的 y 值,您仍然需要第三个变量来区分堆栈中的内容。
  • 如上所述,如果每个 x 轴值有多个变量,则“堆叠”是有意义的。但是,查看您的代码,position = 'fill' 参数在这里没有多大意义。试试这样的:ggplot(data = mydata, aes(x=year)) + geom_col(aes(y=percent, fill = percent))
  • @GregorThomas 添加你的答案

标签: r ggplot2


【解决方案1】:

ggplot 只会绘制那里的数据。您想要包含隐含但实际上并不存在的数据,(1 - percent)。我们将明确地创建它,然后绘图将很容易。

data %>%
  mutate(percent = 1 - percent, type = "not there") %>%
  bind_rows(data) %>%
  mutate(type = coalesce(type, "there")) %>%
  ggplot(aes(x = year, y = percent, fill = type)) +
  geom_col() +
  scale_y_continuous(labels = scales::percent)

如今,geom_colgeom_bar(stat = 'identity') 更受欢迎,并且默认情况下会堆叠。

当然,将标签和颜色更改为您想要的任何颜色。


使用此示例数据

data = read.table(text = '   year   percent
1: 2015   0.16
2: 2016   0.23
3: 2017   0.14
4: 2018   0.64
5: 2019   0.15
6: 2020   0.24', header = T)

【讨论】:

    猜你喜欢
    • 2019-09-27
    • 1970-01-01
    • 1970-01-01
    • 2019-06-08
    • 2021-12-22
    • 1970-01-01
    • 2018-03-15
    • 2021-05-31
    • 2019-11-25
    相关资源
    最近更新 更多