[英]Geom_bar with position = 'fill', hlines for means
我正在尝试绘制一个图表,该图表显示每月两个客户组(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")
应该做这个图:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.