Search code examples
rggplot2mcmc

Reverse x-axis factor levels of mcmc areas after coord_flip


I have a data frame of draws from a Bayesian posterior distribution for three different variables, and I would like to plot them as mcmc_areas.

When I do, the variable names are on the y axis and the draw values are on the y axis. When I use coord_flip to switch the variable names to the x axis, they are reversed.

The other solutions I have seen involve modifying the original dataset or the aes in ggplot to include factor levels, which my data don't have.

How can I reverse the order of the variable names on the x-axis so they read var1, var2, var3 from left to right?

enter image description here

library(bayesplot)
library(ggplot2)

var1 <- c(-0.06002548, -0.02066638, -0.04869878, -0.03085879, -0.04363278, -0.04427182)
var2 <- c(-0.011345631, -0.033393275, -0.037143247, -0.012890959, -0.031249614, -0.001547747)
var3 <- c(-0.05907443, -0.06544918, -0.05831428, -0.04964141, -0.05206038, -0.05726436)

df <- data.frame(var1, var2, var3)

plot <- mcmc_areas(test, pars = c("var1","var2","var3"),
                   point_est = "mean",
                   prob = .95)
ggtest <- plot + coord_flip()

Solution

  • One option would be to reverse order in which you pass your variables to mcmc_areas to get the desired order after flipping:

    library(bayesplot)
    library(ggplot2)
    
    mcmc_areas(df, pars = rev(c("var1","var2","var3")),
               point_est = "mean",
               prob = .95) +
      coord_flip()
    

    Second option would be to set the desired order via the limits argument of scale_y_discrete. Note. Doing so slightly changes the look of the plot. To fix that I set the expand argument equal to values set by mcmc_areas which I extracted from plot$scales$scales[[1]]$expand.

    mcmc_areas(df, pars = c("var1","var2","var3"),
               point_est = "mean",
               prob = .95) +
      coord_flip() +
      scale_y_discrete(limits = c("var1","var2","var3"), expand = c(0.1, 0, 0.1, 0.666666666666667))
    #> Scale for 'y' is already present. Adding another scale for 'y', which will
    #> replace the existing scale.