# How to customize spaghetti plot from conditional_effects()

I’m trying to customize the output of conditional_effects() so that values within a certain range have a different color.

I’m able to store the info from conditional_effects() into a data.frame that I can manipulate

Ketone_NDF_plot=plot(conditional_effects(Ketone_NDF,spaghetti=FALSE),plot=FALSE)[[3]]
Ketone_NDF_est <- as.data.frame(Ketone_NDF_plot[[1]])

> names(Ketone_NDF_est )
[1] "npe_to_ap"   "pos_neg_dn"  "class_focal" "fai"         "name_focal"
[6] "cond__"      "effect1__"   "estimate__"  "se__"        "lower__"
[11] "upper__"


And was able to generate the following plot

I’m wondering how I can achieve the same thing but as a spaghetti plot rather than just line and credible envelope.

Any advice will be much appreciated!

Here’s some example code from a project I’m working on that should help you do what you’re trying to

# Uses packages tidyverse, brms, scales, and latex2exp

# Make the plot object
spagetti_plot <- plot(
conditional_effects(
zib_femleg_cond_fit_2,
effects = "time",
prob = 0.89,
spaghetti = TRUE
),
theme = theme_bw()
)

# You can make subsequent aesthetic tweaks by referencing the underlying ggplot2 object
spagetti_plot_edited <- spagetti_plot$time + # Adjust the breaks along the y axis scale_y_continuous(breaks = scales::pretty_breaks(n = 5)) + # Adding Labels to the X and Y axis labs( y = TeX('Y |$\\alpha_{j}+\\gamma_{j}Time_{tj}\\times\\gamma_{j}Conflict_{tj}\$'),
x = TeX("Time")
)

# Render the plot to a file instead of printing it to the viewer because spagetti plots tend to crash R Studio
ggsave(
filename = "Figure_1A.png",
plot = spagetti_plot_edited,
device = "png",
width = 16,
height = 10,
units = "in",
dpi = "retina",
type = "cairo",
limitsize = FALSE
)


Alternatively, you can use tidybayes and ggplot2 directly as shown here Extracting and visualizing tidy draws from brms models • tidybayes (mjskay.github.io)

Thanks for that! That definitely got me started.

I ended up settling on this solution, which is close enough to what I was going for.

Ketone_NDF_test_plot=conditional_effects(Ketone_NDF,effects = "ndf_kcal_low",spaghetti=TRUE)
Ketone_NDF_test_plot_data <- attr(Ketone_NDF_test_plot[[1]], "spaghetti")
Ketone_NDF_testplot_2 <- ggplot(Ketone_NDF_test_plot_data, aes(x = effect1__, y = estimate__, group = sample__))+
geom_line(color = alpha("#0000FF",.2))+geom_link2(aes(colour = after_stat( x< 300)))
Ketone_NDF_testplot_2


2 Likes