使用ggplot的RDD图,过渡区域将线延伸到截止点

使用ggplot的RDD图,过渡区域将线延伸到截止点,r,ggplot2,R,Ggplot2,考虑以下关于劳动力参与和年龄的数据框架。在65岁时,我们已经达到了领取养老金的年龄,我们对劳动力供给在领取养老金之前和之后的反应很感兴趣。因此,我们也可以绘制一个图,不考虑养老金资格年龄周围的点,因为它可能会引起一些噪音 df<-data.frame( c(63, 63.5, 64, 64.5, 65, 65.5, 66, 66.5, 67), c(0.8, 0.7, 0.65, 0.5 , 0.5, 0.5, 0.15, 0.1 ,0)) colnames(df)<-c("age

考虑以下关于劳动力参与和年龄的数据框架。在65岁时,我们已经达到了领取养老金的年龄,我们对劳动力供给在领取养老金之前和之后的反应很感兴趣。因此,我们也可以绘制一个图,不考虑养老金资格年龄周围的点,因为它可能会引起一些噪音

df<-data.frame( c(63, 63.5, 64, 64.5, 65, 65.5, 66, 66.5, 67), c(0.8, 0.7, 0.65, 0.5 , 0.5, 0.5, 0.15, 0.1 ,0))

colnames(df)<-c("age", "labor_force_participation")

df$pensionbreak<-cut(df$age,
                     breaks = c(-Inf, 64.4,65.5,Inf),
                     labels = c("prior pension", "transition area", "after pension"))

#Plot the graph without taking into account the transition area
p  + 
  geom_smooth(
    data = subset(df, pensionbreak != "transition area"),
    method = "lm", se = TRUE
  ) +
  xlab("age") + 
  ylab("fraction of males working") + 
  labs(color = "Retirement") + 
  theme_bw()

df您可以按如下方式进行操作-虽然不是很优雅,但可以正常工作:)

require(tidyverse)
需要(建模器)
#这是你的子集
df_列车%过滤器(养老金中断!=“过渡区”)
df_预测%
突变(数据pred=map(数据,我的预测,df预测,劳动力参与~年龄))%>%
unnest(数据预处理)
ggplot()+
#对该行使用type==1(预测)
geom_线(数据=dat%>%过滤器(类型==1),
aes(x=年龄,y=劳动力参与度,col=养老金中断),
linetype=“虚线”)+
#使用类型==2(原始数据)作为置信域
geom_平滑(数据=dat%>%过滤器(类型==2),
aes(x=年龄,y=劳动力参与度,col=养老金中断),
方法=“lm”)+
xlab(“年龄”)+
ylab(“男性工作比例”)+
实验室(color=“退休”)+
主题_bw()

谢谢你的回答。不过,我还有一个问题。如果你想创建一个有两个分界点的图,你会如何重新格式化你的代码。更准确地说,假设我也想想象一下63.5岁时是否有跳跃。所以我在这一点上画了一条虚线,在65岁的时候画了一条虚线。你知道我如何用这段代码做到这一点吗?提前谢谢。
require(tidyverse)
require(modelr)

# This is your subsetting
df_train <- df %>% filter(pensionbreak != "transition area")
df_predict <- tibble(age = 65, labor_force_participation = 0.5)

my_predictor <- function(x, pred, formula) {
  mod <- lm(formula, data = x)
  # This returns two types
  # type 1 is the predicted data
  # type 2 is the original data 
  bind_rows(pred, x) %>% 
    add_predictions(mod, var = "labor_force_participation") %>% 
    bind_rows(x, .id = "type")
}

# This applies the above function on your data - seperated by 
# the pensionbreak groups of data
dat <- df_train %>% 
  nest(data = c(age, labor_force_participation)) %>% 
  mutate(data_pred = map(data, my_predictor, df_predict, labor_force_participation ~ age)) %>% 
  unnest(data_pred) 

ggplot() +
  # Using type == 1 (predictions) for the line
  geom_line(data = dat %>% filter(type == 1),
            aes(x = age, y = labor_force_participation, col = pensionbreak),
            linetype = "dashed") +
  # Using type == 2 (original data) for the confidence area
  geom_smooth(data = dat %>% filter(type == 2),
              aes(x = age, y = labor_force_participation, col = pensionbreak),
              method = "lm") +
  xlab("age") + 
  ylab("fraction of males working") + 
  labs(color = "Retirement") + 
  theme_bw()