Customizing marginal_smooth plots

Hi,
I’ve looked around here and on the old brms forum but can’t quite figure out how to extract the ggplot2 object from marginal_smooths(). I’d like to do some customization like adding geom_points() from the primary data and changing the theme.

I have tried plot1 <- plot( marginal_smooths( fit ) ) , but then can’t figure out what within the plot1 object can be extracted and how it can be integrated into a ggplot2 graphic.

Thanks!

Please also provide the following information in addition to your question:

  • Operating System: Win 10
  • brms Version: 2.3.1

The plot method returns a list of ggplot objects, which is explained in the doc of ?marginal_effects.

Does that work through the marginal_smooths function or do I have to do it differently using marginal_effects? This is what I get and I don’t see what is the ggplot2 object I’d extract:

plot1 <- marginal_smooths(gam1)
str(plot1)
List of 1
mu: s(disp):'data.frame': 100 obs. of 5 variables: .. disp : num [1:100] 71.1 75.1 79.2 83.2 87.3 …
estimate__: num [1:100] 11.04 10.43 9.82 9.2 8.59 ... .. se__ : num [1:100] 1.186 1.067 0.967 0.854 0.77 …
lower__ : num [1:100] 8.52 8.18 7.78 7.36 6.94 ... .. upper__ : num [1:100] 13.3 12.5 11.7 10.8 10.1 …
…- attr(, “response”)= chr “mu: s(disp)”
…- attr(
, “effects”)= chr “disp”
…- attr(, “surface”)= logi FALSE
…- attr(
, “points”)=‘data.frame’: 32 obs. of 1 variable:
… …$ disp: num [1:32] 160 160 108 258 360 …
…- attr(*, “too_many_covars”)= logi FALSE

  • attr(*, “class”)= chr “brmsMarginalEffects”
  • attr(*, “smooths_only”)= logi TRUE

plot(marginal_smooths(gam1)) is the same object class as plot(marginal_effects(gam1))

The help file says:
“The corresponding plot method returns a named list of ggplot objects, which can be further customized using the ggplot2 package”

but I’m not sure what to extract - I see the ggplot attributes and functions within “layers” in the plot call, but not what is an extractable object.

gg <- plot(marginal_smooths(gam1))[[1]]
gg + xlab(“abc”)

1 Like

This is what I get -

plot1 <- plot(marginal_smooths(gam1))
plot1 + theme_bw()
NULL

plot1 <- plot(marginal_smooths(gam1))
plot1 + xlab(“abc”)
Error in plot1 + xlab(“abc”) : non-numeric argument to binary operator

Oh I see, I left out the [[1]], works now.

Thanks!

One more question - I’m trying to combine the marginal smooth plot with a separate plot, just using the mtcars data:
gam1 <- brm(mpg ~ s(displ) , data=mtcars)
plot1 <- plot(marginal_smooths(gam1))[[1]]

plot1 + geom_point(data=mtcars, aes(x=disp, y=mpg), color=“Red”, cex=3)

Error in FUN(X[[i]], …) : object ‘lower__’ not found

This is slowly becoming a pure ggplot issue ;-)

you have to use inherit.aes = FALSE in geom_point().

I know, but you’re SO much easier to get in touch with than Hadley :)

Thanks again!
Paul