ggplot2中随时间变化的总和与总计

时间:2019-06-29 03:47:57

标签: r ggplot2 bar-chart

最简单的解释方法是通过这张图片:enter image description here

我想制作一个堆叠的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选项-这里的方向有些混乱。

1 个答案:

答案 0 :(得分:3)

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

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")

enter image description here

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

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

enter image description here

或使用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)) +

enter image description here