Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I specify y-limits in the plots produced by brms::marginal_effects()?

Tags:

plot

r

axes

stan

Here's my example code. I'd like to produce several variations of the same plot, so enforcing identical y-limits is important for visual comparison.

library(brms)

# data
sgf <- c(rep("A",10),rep("B",10))
Vs  <- c(221, 284, 211, 232, 254, 
         260, 239, 219, 226, 232, 
         388, 399, 421, 419, 332, 
         387, 399, 398, 438, 411)
vspr.df <- data.frame(sgf, Vs)

# perform fit
fit <- brm(formula = Vs ~ sgf,
  data = vspr.df,
  family = lognormal(),
  prior = NULL,
  chains=3,
  iter=300,
  warmup=100)

p <- marginal_effects(fit)
plot(p)
plot(p, ylim=c(0,350))   # no effect
plot(p, ylim=c(0,3500))  # no effect

My preferred result is for each of the last 3 lines to result in a plot with different Y limits.

like image 770
nivek Avatar asked Dec 14 '25 04:12

nivek


1 Answers

So plot(p) here actually produces a list of ggplot objects, as can been seen from looking at the source of brms:::plot.brmsMarginalEffects. Also, the help file (?marginal_effects) reads:

The corresponding plot method returns a named list of ggplot objects, which can be further customized using the ggplot2 package.

The list items are per effect of interest.

Regardless, we can choose the first element of this list and then use ylim from ggplot to change the limits:

plot(p)[[1]] + ggplot2::ylim(0, 1000)

Or use the variable name directly:

plot(p)$sgf + ggplot2::ylim(0, 1000)

Both give:

enter image description here

For more control over the axis, use ggplot2::scale_y_continuous.

like image 174
Axeman Avatar answered Dec 16 '25 21:12

Axeman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!