给定百分比,如何绘制堆积的条形图?

时间:2020-03-11 17:03:05

标签: r ggplot2

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

鉴于以下数据,我希望x轴上的年份为y轴,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')

1 个答案:

答案 0 :(得分: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)

enter image description here

如今,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)