Editing conditional effects plots in ggplot2

Hi!

I am trying to edit these conditional effects plots, where I overlay the raw data with the model generated trends.

I have run into two issues so far, the first is that my legend lines are blue, which is not reflective of the actual colors of the trend lines on my graph.

The second issue is that I modeled a standardized variable I did this by subtracting the mean from each observation and then dividing by the sd * 2. Is there any way I can “untransform” my x axis on these graphs so that I can look at the trends on their original scale?

set.seed(123)  # For reproducibility

# Generate fake data
n <- 200
distance <- runif(n, 0, 5)  # Random distances between 0 and 5
stdist <- (distance - mean(distance)) / (2 * sd(distance))  # Standardized distance
treatment <- sample(0:1, n, replace = TRUE)  # 0 = Ablated, 1 = Intact

# Response variable with interaction effect
response <- 2 - 1.5 * stdist + 1.2 * treatment - 0.8 * stdist * treatment + rnorm(n, 0, 0.5)

# Create dataframe
fake_data <- data.frame(distance, stdist, treatment = factor(treatment, labels = c("Ablated", "Intact")), response)

example <- brm(response~ treatment * stdist, data = fake_data,    family = gaussian())

fakece = conditional_effects(example, effects = "stdist:treatment") 

plot(fakece)[[1]] +
  geom_point(data=fake_data, aes(x = stdist, y = response, color = treatment),
             inherit.aes=FALSE, alpha=0.5) +
  guides(colour="none")+
  scale_fill_discrete(name = "Treatment", labels = c("Ablated", "Intact")) +
  xlab(" Standardized Distance (m)") +
  ylab("Response")

You can do this many ways, but for example:

  1. Use + aes() to directly update the aesthetics of the existing plot and undo the scaling
  2. Use both scale_fill_discrete and scale_color_discrete to update and merge both legends.
plot(fakece)[[1]] +
  aes(x = stdist * (2 * sd(distance)) + mean(distance)) +
  geom_point(
    aes(x = distance, y = response, color = treatment),
    fake_data, inherit.aes=FALSE, alpha = 0.5, show.legend = FALSE
  ) +
  scale_fill_discrete(name = "Treatment", labels = c("Ablated", "Intact")) +
  scale_color_discrete(name = "Treatment", labels = c("Ablated", "Intact")) +
  xlab(" Distance (m)") +
  ylab("Response")

6 Likes

Wow! This is so awesome, thank you so much!!!

1 Like