1

I am trying to create a plot in R that is a combination of a marginal effects slope line and a scatterplot of some averaged values. I can create both graphs separately, but I cannot figure out how to make a plot that includes both of these visuals overlapped.

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))

Is this possible to do? So far I have received warnings saying it does not recognize the data or it outputs NULL.

  • 2
    Try `plot1 + geom_point(data = t1, aes(x = mean_time, y = mean_dist), inherit.aes = FALSE)`. If working, add `+ geom_label( ... )` in the same fashion. ( I didn't run the code though ) – markus Dec 16 '19 at 19:21
  • Thank you for this suggestion! This worked! – Emily CLine Dec 16 '19 at 22:53

0 Answers0