我正在尝试绘制一个图表,显示两个客户组(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组的平均百分比,比如this。
发布于 2019-08-19 15:11:34
您希望预先计算关键日期之前和之后的平均值,然后将它们添加到图中。如下所示:
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")
应该画成这个图:
https://stackoverflow.com/questions/57551241
复制相似问题