r - 位置 = 'fill' 的 Geom_bar,hlines 表示平均值
问题描述
我正在尝试绘制一个图表,显示每个月两个客户组(1-5 和 6-8)授予贷款的相对百分比。我是这样做的:
df <- data.frame(time=rep(seq.Date(as.Date('2015-01-01'),as.Date('2018-01-01'), by='month'),2),
key = c(rep('1-5',37),rep('6-8',37)), value = c(round(rnorm(37,400,20)),round(rnorm(23,100,10)),
round(rnorm(14,250,10))))
ggplot(df,aes(x=time,y=value,fill=key))+
geom_bar(stat = "identity",position = "fill")+
geom_vline(xintercept = as.numeric(as.Date('2016-12-01')), size=1)
我想要包括 2017 年之前和之后 6-8 组的平均百分比,类似这样。
解决方案
您想预先计算关键日期之前和之后的平均值,然后将它们添加到绘图中。像这样的东西:
library(ggplot2)
library(dplyr)
library(tidyr)
df <-
data.frame(
time = rep(seq.Date(
as.Date('2015-01-01'), as.Date('2018-01-01'), by = 'month'
), 2),
key = c(rep('1-5', 37), rep('6-8', 37)),
value = c(round(rnorm(37, 400, 20)), round(rnorm(23, 100, 10)),
round(rnorm(14, 250, 10)))
)
# calculate the percents
(
dd <- df %>%
spread(key, value) %>%
mutate(f15=`1-5`/(`1-5`+`6-8`)) %>%
mutate(f68=1-f15)
)
# get averages for before and after 2016-12-01
(
mnp <- dd %>%
mutate(ba=ifelse(time > as.Date('2016-12-01'), "after", "before")) %>%
group_by(ba) %>%
mutate(mnp=mean(f68))
)
# add to plot
ggplot(df, aes(x = time, y = value, fill = key)) +
geom_bar(stat = "identity", position = "fill") +
geom_vline(xintercept = as.numeric(as.Date('2016-12-01')), size = 1) +
geom_point(data=mnp, aes(x=time, y=mnp), pch="-", size=5, inherit.aes = FALSE, color="blue")
应该制作这个情节:
推荐阅读
- bpmn - 如何正确实现可以在过程中的任何时候触发的终止结束事件?
- android - 尝试访问测试资源时在浓缩咖啡上获取 Resources$NotFoundException
- javascript - 如何在某些条件下同时激活多个按钮?
- r - 将计数添加到 X 轴标签中的每个组
- r - 在r中为条形图添加标签
- python - AWS Sagemaker InvokeEndpoint:操作:找不到账户的终端节点
- python - 了解用于培训目的的自定义数据生成器
- python-3.x - 增加 Python 对象的引用计数
- javascript - 如何将 .then 更改为 trycach?
- javascript - 如何使用 Jest 对 Express 控制器进行单元测试