r - 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
选项——只是对这里的方向有点困惑。
解决方案
以下是一些稍微调整的示例数据,以使形状更清晰:
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)) +
推荐阅读
- javascript - 如果 then 有多行代码,则在 Promise Chaining 中出现未定义的错误
- python - 删除同一字符串中特定两个字符后的数字
- react-native - 如何在 onError 回调中使用异步错误处理程序?
- kotlin - 使用循环将 arrayList 添加到 HashMap [kotlin 代码]
- python - Kodi 插件:如何缓存/加载数据?
- python - 使用 socketio 连接树莓派
- json - 颤振创建json或添加列表映射
- c++ - 如何使用队列将字符串转换为大写?
- python-3.x - 在networkx中添加带有节点名称的描述
- java - 项目启动时为 MySQL 数据库打开的连接数