Jeremy
Jeremy

Reputation: 2000

How to make the plots for some variables invisible?

I'm using the great dwplot package (which is built on ggplot) to create dot-whisker plots. They look great, but to present my results I'd love to be able to reveal one variable (one row) at a time. So, the first plot has the result invisible for all but Row 1, the second plot has Row 1 and Row 2 visible, etc.

I'm wondering if there is a good way to do that? For example, is there a way to set just a subset of variables to have alpha = 0?

For example, running

library(dotwhisker)
dwplot(lm(mpg ~ wt + gear + carb, data = mtcars))

gives the following plot.

enter image description here

I want to create a plot where the 'gear' and 'carb' text appears on the left, but the plots do not appear. I can then sequentially reveal the coefficients and the confidence intervals.

Upvotes: 2

Views: 826

Answers (1)

pogibas
pogibas

Reputation: 28379

Here's a solution where you iterate through predictors (using for loop) and pass them to dwplot.
This solution first fits the model on all predictors and then passes only a subset of them (following predictors have only term identifier, statistics are passed as NA)

library(dotwhisker)
# Final result
plots <- list()

# Create a model (using tidy to easily subset)
fit <- broom::tidy(lm(mpg ~ wt + gear + cyl, mtcars))

# Iterate through predictors (#1 is intercept)
for(i in 2:nrow(fit)) {
    # empty terms
    if (i < nrow(fit)) {
        # Add following predictors as NA
        terms <- data.frame(term = fit[(i + 1):nrow(fit), ]$term)
    } else {
        terms <- NULL
    }
    plots[[i - 1]] <- dwplot(dplyr::bind_rows(fit[1:i, ], terms)) + 
                          # Add fixed scales that all plots
                          coord_cartesian(xlim = c(-5.5, 1.5))
}

# Final result is stored in list plots
ggpubr::ggarrange(plotlist = plots)

enter image description here

Upvotes: 3

Related Questions