首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Geom_bar with position = 'fill',hline表示均值

Geom_bar with position = 'fill',hline表示均值
EN

Stack Overflow用户
提问于 2019-08-19 14:09:18
回答 1查看 58关注 0票数 0

我正在尝试绘制一个图表,显示两个客户组(1-5和6-8)每月发放贷款的相对百分比。我是这样做的:

代码语言:javascript
运行
复制
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)

The result

我想要的是包括2017年之前和之后6-8组的平均百分比,比如this

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-19 15:11:34

您希望预先计算关键日期之前和之后的平均值,然后将它们添加到图中。如下所示:

代码语言:javascript
运行
复制
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")

应该画成这个图:

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57551241

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档