1

我正在尝试在 R 中创建一个图,它是边际效应斜率线和一些平均值的散点图的组合。我可以分别创建两个图表,但我不知道如何制作一个包含这两个重叠视觉效果的图。

library(nycflights13)
library(tidyverse)

# I want a graph with a marginal effects slope line layered with 
# a scatter plot of some averaged values. 


df <- flights

# a mixed effects model with random intercepts
lm1 <- lmer(distance ~ air_time + (1|carrier), data = df)
summary(lm1)

# plotting the model made above
plot1 <- sjPlot::plot_model(lm1, type = "pred") 
show(plot1)

# making a table of averaged values per month
t1 <- df%>%
  filter(!is.na(air_time)) %>%
  group_by(month) %>%
  summarise(mean_dist = mean(distance),
            mean_time = mean(air_time))

# making a scatterplot with text labels of those averaged values
plot2 <- 
  ggplot(t1)+
  geom_point(aes(x = mean_time, y = mean_dist)) + 
  geom_text(mapping = aes(x = mean_time, y = mean_dist, label = month), position = position_jitter(height = 1, width = .5))

show(plot2)


# I want to combine these two plots. 
# I have tried the following: 

plot1[[1]] + 
  geom_point(aes(x = mean_time, y = mean_dist, data = t1)) + 
  geom_text(mapping = aes(x = mean_time, y = mean_dist, label = month, data = t1), position = position_jitter(height = 1, width = .5))

plot1[[1]] +
  ggplot(t1) +
  geom_point(aes(x = mean_time, y = mean_dist)) + 
  geom_text(mapping = aes(x = mean_time, y = mean_dist, label = month), position = position_jitter(height = 1, width = .5))

这可能吗?到目前为止,我收到警告说它无法识别数据或输出 NULL。

4

0 回答 0