### Install Latest Release Version Source: https://github.com/fsolt/dotwhisker/blob/master/docs/index.html Use this command to install the latest stable version of the dotwhisker package from CRAN. ```r install.packages("dotwhisker") ``` -------------------------------- ### Install Latest Development Version Source: https://github.com/fsolt/dotwhisker/blob/master/docs/index.html Use this command to install the latest development version of the dotwhisker package directly from GitHub. ```r if (!require("remotes")) install.packages("remotes"); remotes::install_github("fsolt/dotwhisker") ``` -------------------------------- ### Rescale regression results with by_2sd Source: https://github.com/fsolt/dotwhisker/blob/master/docs/reference/by_2sd.html This example demonstrates how to use the `by_2sd` function to rescale regression results from a linear model. It first tidies the model output and then applies `by_2sd` using the original `mtcars` dataset. ```R library(broom) library(dplyr) data(mtcars) m1 <- lm(mpg ~ wt + cyl + disp, data = mtcars) m1_df <- tidy(m1) %>% by_2sd(mtcars) # create data frame of rescaled regression results ``` -------------------------------- ### Integrating Custom Statistics with Bracket Annotations Source: https://github.com/fsolt/dotwhisker/blob/master/docs/articles/dotwhisker-vignette.html This example demonstrates a workaround for integrating custom model fit statistics with bracket annotations. It involves separately generating model fits and manually merging them with a bracket-enhanced dot-whisker plot using `gridExtra` and `patchwork`. ```r library(gridExtra) library(patchwork) three_brackets <- list( c("Overall", "Weight", "Weight"), c("Engine", "Cylinders", "Horsepower"), c("Transmission", "Gears", "Manual") ) plot_brackets <- { dwplot(m3, vline = geom_vline( xintercept = 0, colour = "grey60", linetype = 2 )) |> # plot line at zero _behind_ coefs relabel_predictors( c( wt = "Weight", # relabel predictors cyl = "Cylinders", disp = "Displacement", hp = "Horsepower", gear = "Gears", am = "Manual" ) ) + xlab("Coefficient Estimate") + ylab("") + ggtitle("Predicting Gas Mileage") } |gt add_brackets(three_brackets, fontSize = 0.3) plot_brackets / tableGrob( dotwhisker:::dw_stats( m3, stats_digits = 2, stats_compare = FALSE ), ) ``` -------------------------------- ### Plot Multiple Models with Customizations and Relabeling Source: https://github.com/fsolt/dotwhisker/blob/master/docs/reference/dwplot.html Plots regression coefficients from multiple models generated on the fly, with extensive customization of plot elements, labels, and theme. This example demonstrates advanced usage with data manipulation and ggplot2 theming. ```R # Plot regression coefficients from multiple models on the fly mtcars %>% split(.$am) %>% purrr::map(~ lm(mpg ~ wt + cyl + disp, data = .x)) %>% dwplot() %>% relabel_predictors(c(wt = "Weight", cyl = "Cylinders", disp = "Displacement")) + theme_bw() + xlab("Coefficient") + ylab("") + geom_vline(xintercept = 0, colour = "grey60", linetype = 2) + ggtitle("Predicting Gas Mileage, OLS Estimates") + theme(plot.title = element_text(face = "bold"), legend.position = c(.995, .99), legend.justification = c(1, 1), legend.background = element_rect(colour="grey80"), legend.title.align = .5) + scale_colour_grey(start = .4, end = .8, name = "Transmission", breaks = c("Model 0", "Model 1"), labels = c("Automatic", "Manual")) #> Warning: The `legend.title.align` argument of `theme()` is deprecated as of ggplot2 #> 3.5.0. #> ℹ Please use theme(legend.title = element_text(hjust)) instead. #> Warning: A numeric `legend.position` argument in `theme()` was deprecated in ggplot2 #> 3.5.0. #> ℹ Please use the `legend.position.inside` argument of `theme()` instead. ``` -------------------------------- ### Plot Directly Built Tidy Data Frame with Customizations Source: https://github.com/fsolt/dotwhisker/blob/master/docs/articles/dotwhisker-vignette.html Plot a directly constructed tidy data frame using `dwplot`. This example includes adding a vertical line at zero, customizing the theme, and adjusting legend position and title. ```R dwplot(by_trans, vline = geom_vline( xintercept = 0, colour = "grey60", linetype = 2 )) + # plot line at zero _behind_ coefs theme_bw(base_size = 4) + xlab("Coefficient Estimate") + ylab("") + ggtitle("Predicting Gas Mileage by Transmission Type") + theme( plot.title = element_text(face = "bold"), legend.position = c(0.007, 0.01), legend.justification = c(0, 0), ``` -------------------------------- ### Cluster Results in 'Small Multiple' Plot by Transmission Type Source: https://github.com/fsolt/dotwhisker/blob/master/docs/articles/dotwhisker-vignette.html Demonstrates how to cluster results in a 'small multiple' plot by using the `submodel` variable. This example generates models for different transmission types and combines them into a single tidy data frame for plotting. ```R # Generate a tidy data frame of regression results from five models on # the mtcars data subset by transmission type ordered_vars <- c("wt", "cyl", "disp", "hp", "gear") mod <- "mpg ~ wt" by_trans2 <- mtcars | group_by(am) |> # group data by transmission do(broom::tidy(lm(mod, data = .))) |> # run model on each group rename(submodel = am) |> # make submodel variable mutate(model = "Model 1") |> # make model variable ungroup() for (i in 2:5) { mod <- paste(mod, "+ ", ordered_vars[i]) by_trans2 <- rbind( by_trans2, mtcars | group_by(am) | do(broom::tidy(lm(mod, data = .))) | rename(submodel = am) | mutate(model = paste("Model", i)) | ungroup() ) } # Relabel predictors (they will appear as facet labels) by_trans2 <- by_trans2 | select(-submodel, everything(), submodel) | relabel_predictors( c( ``` -------------------------------- ### Add Labelled Brackets to Dot-and-Whisker Plot Source: https://github.com/fsolt/dotwhisker/blob/master/docs/reference/add_brackets.html This example demonstrates how to use `add_brackets` to group predictors in a dot-and-whisker plot. It requires the `dplyr` and `dotwhisker` packages. The plot is generated using `dwplot` and then customized with `add_brackets` to label groups of variables. ```r library(dplyr) m1 <- lm(mpg ~ wt + cyl + disp, data = mtcars) two_brackets <- list(c("Engine", "Cylinder", "Displacement"), c("Not Engine", "Intercept", "Weight")) {dwplot(m1, show_intercept = TRUE) %>% relabel_predictors("(Intercept)" = "Intercept", wt = "Weight", cyl = "Cylinder", disp = "Displacement") + theme_bw() + xlab("Coefficient") + ylab("") + theme(legend.position="none") + geom_vline(xintercept = 0, colour = "grey50", linetype = 2)} %>% add_brackets(two_brackets) ``` -------------------------------- ### Filter Model Estimates by Regular Expression Source: https://github.com/fsolt/dotwhisker/blob/master/docs/articles/dotwhisker-vignette.html Use `filter()` with `grepl()` on the 'term' column of a tidy data frame to exclude specific model estimates, such as factor levels starting with a certain pattern. ```R # Transform cyl to factor variable in the data m_factor <- lm(mpg ~ wt + cyl + disp + gear, data = mtcars |> mutate(cyl = factor(cyl))) # Remove all model estimates that start with cyl* m_factor_df <- broom::tidy(m_factor) | filter(!grepl('cyl*', term)) ``` -------------------------------- ### Load Libraries and Run Regression Source: https://github.com/fsolt/dotwhisker/blob/master/docs/articles/dotwhisker-vignette.html Loads the dotwhisker and dplyr libraries, then runs a linear regression model using the mtcars dataset. ```R library(dotwhisker) library(dplyr) # run a regression compatible with tidy m1 <- lm(mpg ~ wt + cyl + disp + gear, data = mtcars) ``` -------------------------------- ### Extracting Coefficients from Unsupported Models Source: https://github.com/fsolt/dotwhisker/blob/master/docs/articles/dotwhisker-vignette.html Demonstrates how to extract coefficients from a model object not directly supported by `tidy` or `parameters::parameters` and prepare them for `dwplot`. ```R # the ordinal regression model is not supported by tidy m4 <- ordinal::clm(factor(gear) ~ wt + cyl + disp, data = mtcars) m4_df <- coef(summary(m4)) | data.frame() | tibble::rownames_to_column("term") | rename(estimate = Estimate, std.error = Std..Error) m4_df ``` ```R dwplot(m4_df) ``` -------------------------------- ### Plotting with Custom Shapes and Linetypes Source: https://github.com/fsolt/dotwhisker/blob/master/docs/articles/dotwhisker-vignette.html Shows how to modify the plot to use different shapes for point estimates and linetypes for whiskers, based on the model. ```R dwplot( by_trans, vline = geom_vline( xintercept = 0, colour = "grey60", linetype = 2 ), # plot line at zero _behind_ coefs dot_args = list(aes(shape = model)), whisker_args = list(aes(linetype = model)) ) + theme_bw(base_size = 4) + xlab("Coefficient Estimate") + ylab("") + ggtitle("Predicting Gas Mileage by Transmission Type") + theme( plot.title = element_text(face = "bold"), legend.position = c(0.007, 0.01), legend.justification = c(0, 0), legend.background = element_rect(colour = "grey80"), legend.title.align = .5 ) + scale_colour_grey( start = .1, end = .1, # if start and end same value, use same colour for all models name = "Model", breaks = c(0, 1), labels = c("Automatic", "Manual") ) + scale_shape_discrete( name = "Model", breaks = c(0, 1), labels = c("Automatic", "Manual") ) + guides( shape = guide_legend("Model"), colour = guide_legend("Model") ) # Combine the legends for shape and color ``` -------------------------------- ### Rescaling Coefficients by Two Standard Deviations Source: https://github.com/fsolt/dotwhisker/blob/master/docs/articles/dotwhisker-vignette.html Shows how to use the `by_2sd` function to rescale coefficients in a tidy data frame, facilitating comparison between different predictor types. ```R # Customize the input data frame m1_df_mod <- m1_df | by_2sd(mtcars) | arrange(term) m1_df_mod # rescaled, with variables reordered alphabetically ``` ```R dwplot(m1_df_mod) ``` -------------------------------- ### Generate a 'small multiple' plot Source: https://github.com/fsolt/dotwhisker/blob/master/docs/reference/small_multiple.html This snippet demonstrates how to create a 'small multiple' plot using a list of lm model objects. Ensure the models are defined before calling the function. ```R m1 <- lm(mpg ~ wt + cyl + disp + gear, data = mtcars) m2 <- update(m1, . ~ . + hp) # Generate a 'small multiple' plot small_multiple(list(m1, m2)) ``` -------------------------------- ### dwplot() / dw_plot() Source: https://github.com/fsolt/dotwhisker/blob/master/docs/reference/index.html Creates dot-and-whisker plots of regression results. ```APIDOC ## dwplot() / dw_plot() ### Description Dot-and-Whisker Plots of Regression Results ### Function Signature dwplot() or dw_plot() ### Parameters (No parameters explicitly documented in the source) ### Returns (No return value explicitly documented in the source) ### Example (No example explicitly documented in the source) ``` -------------------------------- ### Prepare Data for Parallel Dot Plots in R Source: https://github.com/fsolt/dotwhisker/blob/master/docs/articles/kl2007_examples.html This code prepares vectors for coefficients, standard errors, and variable names required for plotting regression models. It initializes matrices and vectors with specific values, including handling missing data (NA). ```R #Create Vectors for coefs and standard errors for each model, and variable names #note that we exclude "margin squared" since it doesn't appear in either model coef.matrix <- matrix(c(-.039, NA, .048, -.133, .071, -.795, 1.47, -.036, NA, .036, -.142, .07, -.834, 1.70, -.051, NA, .017, .05, .011, -.532, .775, -.037, -.02, .047, -.131,.072, -.783, 1.45, -.034, -.018, -.035, -.139, .071, -.822, 1.68, -.05, -.023, .016,-.049, .013, -.521, .819),nr=7) ## R2 of the models R2<- c(0.910, 0.910, 0.940, 0.910, 0.910, 0.940) ##standard error matrix, n.variables x n.models se.matrix <- matrix(c(.003, NA, .011, .013, .028, .056, .152, .003, NA, .012, .014, .029, .059, .171, .003, NA, .01, .013, .024, .044, .124, .003, .005, .011, .013, .028, .055, .152, .003, .005, .021, .014, .029, .059, .17, .003,.006, .01, .013, .024, .044, .127),nr=7) ##variable names coef.vec.1<- c(0.18, -0.19,-0.39,-0.09, NA, 0.04,-0.86, 0.39,-3.76, -1.61, -0.34, -1.17, -1.15,-1.52, -1.66, -1.34,-2.89,-1.88,-1.08, 0.20) se.vec.1 <- c(0.22, 0.22, 0.18,.29, NA, 0.08,0.26,0.29,0.36,.19,0.19, 0.22, 0.22,0.25,0.28,0.32,0.48, 0.43,0.41, 0.20) coef.vec.2 <- c(0.27,-0.19, NA, NA, 0.005, 0.04,-0.98,-.36,-3.66, -1.59, -0.45, -1.24, -1.04, -1.83, -1.82, -1.21, -2.77, -1.34, -0.94, 0.13) se.vec.2 <- c(0.22,0.24, NA, NA, 0.004, 0.09 , .31 , .30 , .37 , .21 , .21 , .24 , .24, .29 , .32 , .33 , .49 , .46 , .49 , .26) var.names <- c("Zombie" , "SMD Only", "PR Only", "Costa Rican in PR", "Vote Share Margin", "Urban-Rural Index","No Factional\nMembership", "Legal Professional", "1st Term", "2nd Term", "4th Term", "5th Term","6th Term","7th Term","8th Term","9th Term","10th Term", "11th Term","12th Term", "Constant") y.axis <- length(var.names):1#create indicator for y.axis, descending so that R orders vars from top to bottom on y-axis adjust <- .15 #create object that we will use to adjust points and lines up and down to distinguish between models ``` -------------------------------- ### Display Model Fit Statistics for Multiple Models in dwplot Source: https://github.com/fsolt/dotwhisker/blob/master/docs/articles/dotwhisker-vignette.html To show model fit statistics for a list of models in `dwplot`, pass the list to the function and set `show_stats = TRUE`. The `stats_size` argument controls the text size. ```r dwplot(list(m1, m2, m3), show_stats = TRUE, stats_size = 3) ``` -------------------------------- ### Display Model Fit Statistics in dwplot Source: https://github.com/fsolt/dotwhisker/blob/master/docs/articles/dotwhisker-vignette.html Use `show_stats = TRUE` to display model fit statistics directly below a dot-whisker plot generated by `dwplot`. Adjust `stats_size` to control the text size of the statistics. ```r dwplot(m1, show_stats = TRUE, stats_size = 3) ``` -------------------------------- ### Basic Dot-and-Whisker Plot Source: https://github.com/fsolt/dotwhisker/blob/master/docs/articles/dotwhisker-vignette.html Generates a basic dot-and-whisker plot from a single linear regression model object. ```R dwplot(m1) ``` -------------------------------- ### Build Tidy Data Frame Directly Source: https://github.com/fsolt/dotwhisker/blob/master/docs/articles/dotwhisker-vignette.html Construct a tidy data frame of regression results directly from data subsets without explicitly creating model objects first. This involves grouping data, running `lm` within each group using `do()`, renaming the grouping variable to 'model', and relabeling predictor names. ```R # Run model on subsets of data, save results as tidy df, make a model variable, and relabel predictors by_trans <- mtcars | group_by(am) |> # group data by trans do(broom::tidy(lm(mpg ~ wt + cyl + disp + gear, data = .))) |> # run model on each grp rename(model = am) |> # make model variable relabel_predictors(c( wt = "Weight", # relabel predictors cyl = "Cylinders", disp = "Displacement", gear = "Gear" )) ``` -------------------------------- ### Plotting with Custom Colors and Labels Source: https://github.com/fsolt/dotwhisker/blob/master/docs/articles/dotwhisker-vignette.html Demonstrates how to customize the appearance of a dotwhisker plot, including relabeling the legend for transmission types. ```R dwplot( by_trans, legend.title = "Transmission", vars = c("mpg", "cyl", "disp"), model.labels = c("Automatic", "Manual") ) + theme_bw(base_size = 4) + xlab("Coefficient Estimate") + ylab("") + ggtitle("Predicting Gas Mileage by Transmission Type") + theme( plot.title = element_text(face = "bold"), legend.position = c(0.007, 0.01), legend.justification = c(0, 0), legend.background = element_rect(colour = "grey80"), legend.title.align = .5 ) + scale_colour_grey( start = .3, end = .7, name = "Transmission", breaks = c(0, 1), labels = c("Automatic", "Manual") ) ``` -------------------------------- ### Plotting regression coefficients with custom dot and whisker colors Source: https://github.com/fsolt/dotwhisker/blob/master/NEWS.md Demonstrates how to customize the appearance of regression coefficients and their confidence intervals using dwplot. This includes setting specific colors for the coefficient dots and the whisker lines, and positioning a vertical line behind the coefficients. ```r library(dotwhisker) #> Loading required package: ggplot2 # linear model of interest lm_object <- stats::lm(formula = wt ~ am * cyl, data = mtcars) # creating the plot with dwplot dwplot(x = lm_object, dot_args = list(color = "red"), # color for the dot whisker_args = list(color = "black"), # color for the whisker vline = ggplot2::geom_vline(xintercept = 0, # put vline _behind_ coefs colour = "grey60", linetype = 2, size = 1)) ``` -------------------------------- ### Display Model Fit Statistics for Multiple Models in small_multiple Source: https://github.com/fsolt/dotwhisker/blob/master/docs/articles/dotwhisker-vignette.html Use `show_stats = TRUE` within the `small_multiple` function to display model fit statistics below each plot when visualizing multiple models. `stats_size` adjusts the text size. ```r small_multiple(list(m1, m2, m3), show_stats = TRUE, stats_size = 3) ``` -------------------------------- ### Dot-and-Whisker Plot using dotwhisker Package Source: https://github.com/fsolt/dotwhisker/blob/master/docs/articles/kl2007_examples.html This snippet demonstrates how to recreate the dot-and-whisker plot using the dotwhisker R package. It formats the data into a tidy dataframe and then uses the `dwplot` function to generate the plot, allowing for customization of themes, titles, and annotations. ```R #install.packages("dotwhisker") # uncomment to install from CRAN library(dplyr) library(dotwhisker) library(dplyr) # Format data as tidy dataframe results_df <- data.frame(term=var.names, estimate=coef.vec, std.error=se.vec) # Draw dot-and-whisker plot results_df %>% dwplot(show_stats = FALSE) + theme_bw() + theme(legend.position="none") + ggtitle("Determinants of Authoritarian Aggression\nStevens, Bishin, and Barr (2006)\nvia Kastellec and Leoni (2007)") + geom_vline(xintercept = 0, colour = "grey60", linetype = 2) + annotate("text", x = 1.05, y = 10, size = 4, hjust = 0, label = "R^2 == .15", parse = TRUE) + annotate("text", x = 1.05, y = 9, size = 4, hjust = 0, label = "Adjusted~R^2 == .12", parse = TRUE) + annotate("text", x = 1.05, y = 8, size = 4, hjust = 0, label = "n = 500") ``` -------------------------------- ### Prepare Regression Data for Plotting Source: https://github.com/fsolt/dotwhisker/blob/master/docs/articles/kl2007_examples.html This R code prepares matrices for regression point estimates and standard errors, along with variable names, to be used with a plotting function. It separates data based on the presence of a 'law change' variable for comparative plotting. ```R library(grid) ##point estimates, in a n.variables, n.variables x n.models coef.matrix <- matrix(c(-.039, NA, .048, -.133, .071, -.795, 1.47, -.036, NA, .036, -.142, .07, -.834, 1.70, -.051, NA, .017, .05, .011, -.532, .775, -.037, -.02, .047, -.131,.072, -.783, 1.45, -.034, -.018, -.035, -.139, .071, -.822, 1.68, -.05, -.023, .016,-.049, .013, -.521, .819),nr=7) ## R2 of the models R2<- c(0.910, 0.910, 0.940, 0.910, 0.910, 0.940) ##standard error matrix, n.variables x n.models se.matrix <- matrix(c(.003, NA, .011, .013, .028, .056, .152, .003, NA, .012, .014, .029, .059, .171, .003, NA, .01, .013, .024, .044, .124, .003, .005, .011, .013, .028, .055, .152, .003, .005, .021, .014, .029, .059, .17, .003,.006, .01, .013, .024, .044, .127),nr=7) ##variable names varnames<- c("% of county\nregistration", "Law change", "Log population", "Log median\nfamily income", "% population with\nh.s. education" ,"% population\nAfrican American" ,"Constant") ##exclude intercept coef.matrix<-coef.matrix[-(7,)] se.matrix<-se.matrix[-7,] ## each panel has at most six models, plotted in pairs. ## in each pair, solid circles will be the models with "law change" in the specification ## empty circles, those without "law change" ##we are making a list, define it first as empty Y1 <- vector(length=0,mode="list") #estimates with law change (in the 4th to 6th columns) Y1$estimate <- coef.matrix[,4:6] ##95% confidence intervals Y1$lo <- coef.matrix[,4:6]-qnorm(0.975)*se.matrix[,4:6] Y1$hi <- coef.matrix[,4:6]+qnorm(0.975)*se.matrix[,4:6] ##90% confidence intervals Y1$lo1 <- coef.matrix[,4:6]-qnorm(0.95)*se.matrix[,4:6] Y1$hi1 <- coef.matrix[,4:6]+qnorm(0.95)*se.matrix[,4:6] ##name the rows of Y1 estimate rownames(Y1$estimate) <- varnames[-7] ##no intercept #estimates without law change Y2 <- vector(length=0,mode="list") Y2$estimate <- coef.matrix[,1:3] Y2$lo <- coef.matrix[,1:3]-qnorm(.975)*se.matrix[,1:3] Y2$hi <- coef.matrix[,1:3]+qnorm(.975)*se.matrix[,1:3] Y2$lo1 <- coef.matrix[,1:3]-qnorm(.95)*se.matrix[,1:3] Y2$hi1 <- coef.matrix[,1:3]+qnorm(.95)*se.matrix[,1:3] rownames(Y2$estimate) <- varnames[-7] ``` -------------------------------- ### by_2sd() Source: https://github.com/fsolt/dotwhisker/blob/master/docs/reference/index.html Rescales regression results by multiplying by 2 standard deviations. ```APIDOC ## by_2sd() ### Description Rescale regression results by multiplying by 2 standard deviations ### Function Signature by_2sd() ### Parameters (No parameters explicitly documented in the source) ### Returns (No return value explicitly documented in the source) ### Example (No example explicitly documented in the source) ``` -------------------------------- ### Plot Regression Coefficients from Multiple Models Source: https://github.com/fsolt/dotwhisker/blob/master/docs/reference/dwplot.html Generates a dot-whisker plot comparing regression coefficients from multiple model objects. Models are provided as a list. ```R # Plot regression coefficients from multiple models m2 <- update(m1, . ~ . - disp) dwplot(list(full = m1, nodisp = m2)) ``` -------------------------------- ### Plot Multiple Models with dwplot Source: https://github.com/fsolt/dotwhisker/blob/master/docs/articles/dotwhisker-vignette.html Pass a combined tidy data frame containing results from multiple models to `dwplot` to visualize and compare them. ```R dwplot(two_models) ``` -------------------------------- ### Prepare Tidy Data for Multiple Models Source: https://github.com/fsolt/dotwhisker/blob/master/docs/articles/dotwhisker-vignette.html When plotting results from multiple models, create separate tidy data frames for each model, filter out unwanted terms (like the intercept), and add a 'model' column to identify each model. Then, combine these data frames using `rbind()`. ```R m1_df <- broom::tidy(m1) |> filter(term != "(Intercept)") |> mutate(model = "Model 1") m2_df <- broom::tidy(m2) |> filter(term != "(Intercept)") |> mutate(model = "Model 2") two_models <- rbind(m1_df, m2_df) ``` -------------------------------- ### Customize Dot and Whisker Appearance Source: https://github.com/fsolt/dotwhisker/blob/master/docs/reference/dwplot.html Generates a dot-whisker plot for a single linear model object, allowing customization of the appearance of dots and whiskers. ```R # Change the appearance of dots and whiskers dwplot(m1, dot_args = list(size = 3, pch = 21, fill = "white")) ``` -------------------------------- ### Plot Tidy Data Frame with dwplot Source: https://github.com/fsolt/dotwhisker/blob/master/docs/articles/dotwhisker-vignette.html Directly pass a tidy data frame to `dwplot` to generate a plot of regression coefficients. This is equivalent to passing the original model object. ```R dwplot(m1_df) #same as dwplot(m1) ``` -------------------------------- ### Generate 'Small Multiple' Plot from Tidy Data Source: https://github.com/fsolt/dotwhisker/blob/master/docs/articles/dotwhisker-vignette.html Creates a 'small multiple' plot to visualize regression coefficients from multiple models. The input is a tidy data frame where coefficients have been rescaled using `by_2sd`. Predictors are relabeled for clarity in facet labels. ```R # Generate a tidy data frame of regression results from six models m <- list() ordered_vars <- c("wt", "cyl", "disp", "hp", "gear", "am") m[[1]] <- lm(mpg ~ wt, data = mtcars) m123456_df <- m[[1]] | broom::tidy() | by_2sd(mtcars) | mutate(model = "Model 1") for (i in 2:6) { m[[i]] <- update(m[[i - 1]], paste(". ~ . +", ordered_vars[i])) m123456_df <- rbind(m123456_df, m[[i]] | broom::tidy() | by_2sd(mtcars) | mutate(model = paste("Model", i))) } # Relabel predictors (they will appear as facet labels) m123456_df <- m123456_df | relabel_predictors( c( "(Intercept)" = "Intercept", wt = "Weight", cyl = "Cylinders", disp = "Displacement", hp = "Horsepower", gear = "Gears", am = "Manual" ) ) # Generate a 'small multiple' plot small_multiple(m123456_df) + theme_bw(base_size = 4) + ylab("Coefficient Estimate") + geom_hline(yintercept = 0, colour = "grey60", linetype = 2) + ggtitle("Predicting Mileage") + theme( plot.title = element_text(face = "bold"), legend.position = "none", axis.text.x = element_text(angle = 60, hjust = 1) ) ``` -------------------------------- ### Generate Regression Plot with Grid and Reference Line Source: https://github.com/fsolt/dotwhisker/blob/master/docs/articles/kl2007_examples.html This snippet shows how to create a regression plot with horizontal and vertical grids, and an optional reference line. It handles overlapping confidence intervals and plots point estimates. ```R vgrid <- rectGrob(y=unit(rep(0.5,l.x),"npc"), ##x=unit(x.o[seq(2,l.x,1)],"native"), x=unit(x.o,"native"), width=unit(1,"native"), gp=gpar(lty="dotted",lty=0,fill=c("gray90","gray95"))) } else { vgrid <- NULL } ## ref line if (drawRef) { refline <- segmentsGrob(x0=unit(0.01,"npc"),x1=unit(.99,"npc"),y0=unit(refline,"native"),y1=unit(refline,"native"),gp=gpar(lwd=1*lwd.fact,lty="dashed",col="grey20")) } else { refline <- NULL } ## store ci ci1a <- NULL ci1b <- NULL ci2a <- NULL ci2b <- NULL points2 <- NULL ## if ncol(Y)=5 there are overlapping CIs. the second one here. if(ncol(Y)==5) ci1b <- ci.grob(Y$hi1,Y$lo1,x,lwd=.8*lwd.fact,name="ci1b",plot.arrow=TRUE) ## the first one here. ci1a <- ci.grob(Y$hi,Y$lo,x,lwd=1.2*lwd.fact,name="ci1a") if (!is.null(Y2)) { ## if ncol(Y2)=5 there are overlapping CIs. the second one here. if(ncol(Y2)==5) ci2b <- ci.grob(Y2$hi1,Y2$lo1,x2,lwd=.8*lwd.fact,name="ci2b",plot.arrow=TRUE) ## the first one here. ci2a <- ci.grob(Y2$hi,Y2$lo,x2,lwd=1.2*lwd.fact,name="ci2a") ## point estimates here points2 <- estimates.grob(x2,Y2,fill="white") } if (is.null(labely)) { labely <- aty ##print(paste("labely is ",labely,is.null(labely))) } gplot <- with(Y, ## gTree is a graphical object with the whole plot gTree( children=gList( hgrid,vgrid, refline, ci1a, ci1b, estimates.grob(x,Y), ## if Y2 ci2a, ci2b ,points2 ## box/rectangle around the plot area ##,rectGrob(gp=gpar(lwd=.5*lwd.fact)) ## plot x axis if sp2>0 (we name it xaxis, so we can refer to it later) ,if(sp[2]!=0) xaxisGrob(at=x.o,label=label.x,name="xaxis", gp=gpar(cex=0.8*lwd.fact,lwd=0.6*lwd.fact)) ## plot x axis with no labels if it is not the bottom plot ,if((sp[2]==0)&(!v.grid)) xaxisGrob(at=x.o,label=rep("",length(x.o)), gp=gpar(cex=0.8*lwd.fact,lwd=0.6*lwd.fact)) ## plot y-axis if sp1>0 ,if(sp[1]!=0) yaxisGrob(at=aty,label=labely, gp=gpar(cex=0.7*lwd.fact,lwd=0.6*lwd.fact),main=FALSE,name="yaxis")), ## definition of the viewport (plot area) vp=viewport(width=unit(1, "npc"), height=unit(1, "npc"), ##xscale=c(1,nrow(Y)), xscale=c(1-.5,nrow(Y)+.5), yscale=r.y ##yscale=c(-.1,.1) ,clip=FALSE) )) if (draw==TRUE) { ##draw the plot grid.newpage() fg <- frameGrob(layout=grid.layout(2,2,widths=unit(c(sp[1],1-sp[1]),"npc"),heights=unit(c(1-sp[2],sp[2]),"npc"))) fg <- placeGrob(fg,gplot,col=2,row=1) grid.arrange(fg) } else { gplot } } ``` -------------------------------- ### Estimate Models and Tidy Results Source: https://github.com/fsolt/dotwhisker/blob/master/docs/reference/secret_weapon.html Estimates linear regression models for different groups (clarity levels) and tidies the results into a data frame. This prepares the data for plotting with secret_weapon. ```R library(dplyr) library(broom) # Estimate models across many samples, put results in a tidy data frame by_clarity <- diamonds %>% group_by(clarity) %>% group_by(clarity) %>% do(tidy(lm(price ~ carat + cut + color, data = .))) %>% ungroup %>% rename(model = clarity) ``` -------------------------------- ### Plot Multiple Regression Models Source: https://github.com/fsolt/dotwhisker/blob/master/docs/articles/dotwhisker-vignette.html Draws a dot-and-whisker plot comparing results from three different regression models. The dodge_size argument can be adjusted to control spacing between estimates. ```R m2 <- update(m1, . ~ . + hp) # add another predictor m3 <- update(m2, . ~ . + am) # and another dwplot(list(m1, m2, m3)) ``` -------------------------------- ### Create 'Secret Weapon' Plot for Diamond Clarity Source: https://github.com/fsolt/dotwhisker/blob/master/docs/articles/dotwhisker-vignette.html Generates a 'secret weapon' plot to compare the estimated coefficient for 'carat' across different diamond clarity grades. Requires data to be tidied and grouped by model. ```R data(diamonds) # Estimate models for many subsets of data, put results in a tidy data.frame by_clarity <- diamonds |> group_by(clarity) |> do(broom::tidy(lm(price ~ carat + cut + color, data = .), conf.int = .99)) |> ungroup() |> rename(model = clarity) # Deploy the secret weapon secret_weapon(by_clarity, var = "carat") + xlab("Estimated Coefficient (Dollars)") + ylab("Diamond Clarity") + ggtitle("Estimates for Diamond Size Across Clarity Grades") + theme(plot.title = element_text(face = "bold")) ``` -------------------------------- ### Customizing Model Fit Statistics with dw_stats and stats_tb Source: https://github.com/fsolt/dotwhisker/blob/master/docs/articles/dotwhisker-vignette.html Generate custom model fit statistics using the hidden `dw_stats` function and provide them to `dwplot` via the `stats_tb` argument. This is useful when using customized model outputs or when specific statistics are desired. Ensure models are compatible with the `performance` package. ```r stats_fakeCustom <- dotwhisker:::dw_stats(m1, stats_digits = 2) dwplot( m1_df, show_stats = TRUE, stats_tb = stats_fakeCustom, stats_size = 3 ) ``` -------------------------------- ### Display Directly Built Tidy Data Frame Source: https://github.com/fsolt/dotwhisker/blob/master/docs/articles/dotwhisker-vignette.html Display the constructed tidy data frame, which contains grouped regression results with relabeled predictors. ```R by_trans ``` -------------------------------- ### small_multiple() Source: https://github.com/fsolt/dotwhisker/blob/master/docs/reference/index.html Generates a 'Small Multiple' plot of regression results. ```APIDOC ## small_multiple() ### Description Generate a 'Small Multiple' Plot of Regression Results ### Function Signature small_multiple() ### Parameters (No parameters explicitly documented in the source) ### Returns (No return value explicitly documented in the source) ### Example (No example explicitly documented in the source) ``` -------------------------------- ### Create Tidy Data Frame from Model Source: https://github.com/fsolt/dotwhisker/blob/master/docs/articles/dotwhisker-vignette.html Use the `broom::tidy()` function to convert a model object into a tidy data frame suitable for `dwplot`. This data frame contains columns for term, estimate, and standard error. ```R m1_df <- broom::tidy(m1) # create data.frame of regression results m1_df # a tidy data.frame available for dwplot ``` -------------------------------- ### Create Variable Categories and Braces in Plot Source: https://github.com/fsolt/dotwhisker/blob/master/docs/articles/kl2007_examples.html Sets plot margins and creates an empty plot to add custom brackets and text labels for variable categories. This is helpful for visually grouping related variables in a regression plot. ```r #Create Variable Categories and Braces to go in 2nd plot oldpar <- par(mar=c(2,0,.5,0)) #set margins--- bottom (1st number) and top (3rd number) must be the same as in 1st plot plot(seq(0,1,length=length(var.names)), y.axis, type = "n", axes = F, xlab = "", ylab = "")#call empty plot using type="n" #use a sequence of length 20 so that x and y have same length left.side <- .55#use this to manipulate how far segments are from y-axis #note: getting braces and text in proper place requires much trial and error segments(left.side,20.2,left.side,16.5) #add brackets around MP Type vars segments(left.side,20.2,left.side+.15,20.2) #1 segment at a time segments(left.side,16.5,left.side+.15,16.5) text(.4, 18.5, "MP Type", srt = 90, font = 3, cex = 1.5)#Add text; "srt" rotates to 90 degrees, font = 3 == italics #don't add "Electoral Strength" since it's only 1 variable segments(left.side,15.5,left.side,12.3) #add brackets around "Misc Controls" segments(left.side,15.5,left.side+.15,15.5) #one segment at a time segments(left.side,12.3,left.side+.15,12.3) text(.3, 14, "Misc\nControls", srt = 90, font = 3, cex = 1.5)#Add text; "srt" rotates to 90 degrees, font = 3 == italics segments(left.side,12.15,left.side,1.8) #add brackets around "Seniority" segments(left.side,12.15,left.side+.15,12.15) #one segment at a time segments(left.side,1.8,left.side+.15,1.8) text(.4, 7, "Seniority", srt = 90, font = 3, cex = 1.5)#Add text; "srt" rotates to 90 degrees, font = 3 == italics par(oldpar) ``` -------------------------------- ### Small Multiple Plot with dotwhisker Source: https://github.com/fsolt/dotwhisker/blob/master/docs/articles/kl2007_examples.html Creates a small multiple plot using the `small_multiple` function from the dotwhisker package. It formats data into a tidy dataframe and customizes plot aesthetics like axis limits and themes. ```R # Format data as tidy dataframe model_names <- c("Full Sample\n", "Excluding counties\nw/ partial registration\n", "Full sample w/\nstate year dummies\n") submodel_names <- c("With","Without") model_order <- c(4, 1, 5, 2, 6, 3) results_df <- data.frame(term = rep(varnames[1:6], times = 6), estimate = as.vector(coef.matrix[, model_order]), std.error = as.vector(se.matrix[, model_order]), model = as.factor(rep(model_names, each = 12)), submodel = rep(rep(submodel_names, each = 6), times = 3), stringsAsFactors = FALSE) small_multiple(results_df, show_stats = FALSE) + scale_x_discrete(limits = model_names) + # order the models theme_bw() + ylab("Coefficient Estimate") + geom_hline(yintercept = 0, colour = "grey60", linetype = 2) + theme(axis.text.x = element_text(angle = 45, hjust = 1), ```