首页 > 解决方案 > CumSum 随着时间的推移与 ggplot2 中的总计

问题描述

最简单的解释方法是通过这张图片:在此处输入图像描述

我想制作一个堆叠的ggplot,它显示(以值而不是百分比)一个值随时间的累积总和,同时显示该值在背景中的总“潜力”。

数据集需要看起来像:

+------------+-------+------------------+-----------------+
|    Date    | Value | Cumulative Value | Potential Value |
+------------+-------+------------------+-----------------+
| 2017-01-01 |   100 |              100 |             500 |
| 2018-01-01 |   100 |              200 |             500 |
| 2019-01-01 |   100 |              300 |             500 |
+------------+-------+------------------+-----------------+

#example set:
df <- data.frame(
"Date" = as.Date( c("2017-01-01","2018-01-01","2019-01-01") ), 
"Value" = c(100,100,100),
"Cumulative Value" = c(100,200,300), 
"Potential Value" = c(500,500,500)
)

我的主要尝试是这样的:

ggplot(df, aes(y=`Cumulative.Value`, x=Date)) +
     geom_bar( stat="identity")

然后我开始阅读这个position_stack选项——只是对这里的方向有点困惑。

标签: rggplot2bar-chart

解决方案


以下是一些稍微调整的示例数据,以使形状更清晰:

df <- data.frame(
  "Date" = as.Date( c("2017-01-01","2018-01-01","2019-01-01") ), 
  "Value" = c(100,150,100),
  "Cumulative Value" = c(100,250,350), 
  "Potential Value" = c(500,500,500)
)

使用 geom_area + geom_ribbon 的一种方法:

ggplot(df, aes(y=`Cumulative.Value`, x=Date)) +
  geom_area() +
  geom_ribbon(aes(ymin = `Cumulative.Value`,
                  ymax = `Potential.Value`), fill = "gray80")

在此处输入图像描述

或者两个 geom_cols,后面的潜在一个:

ggplot(df, aes(y=`Cumulative.Value`, x=Date)) +
  geom_col(aes(y = Potential.Value), fill = "gray80") +
  geom_col( stat="identity")

在此处输入图像描述

或者使用 geom_rect,它将显示已知 x 值之间的区域。在这里,我在 30 天后编了一个结束日期,以便我们可以看到结束值。我首先绘制“潜力”一个,以便如果累积超过它,它将被绘制在它的顶部,就像你在最右边的例子一样。

ggplot(df, aes(xmin = Date, 
               xmax = lead(Date, default = max(df$Date) + 30))) +
  geom_rect(aes(ymin = Cumulative.Value, ymax = Potential.Value), fill = "gray80") 
  geom_rect(aes(ymin = 0, ymax = Cumulative.Value)) +

在此处输入图像描述


推荐阅读