Retaining confidence intervals with dwplot in R while setting x axis limits in R

I'm trying to use the ggplot2 and dotwhisker packages in R to display coefficient estimates from a model. One of my covariates has very wide confidence intervals, so the scale of the x-axis is very large. When I set the x-axis limits narrower than the CIs, the CI bars disappear from the plot. Is there a way to retain the CIs, even though they will be cropped?

For example, I produce figure 1:

data(mtcars)
mtest <- lm(mpg ~ cyl + hp + wt, data = mtcars)
dwplot(mtest) 

figure 1 - with confidence intervals but wide axis range

When I try to set the axis limits I lose the CI, as in figure 2:

dwplot(mtest) +  scale_x_continuous(limits = c(-4, 1))

figure 2 - with a narrower axis scale but without the confidence intervals

Thanks!


Solution 1:

A (much) less demanding way to accomplish this than hand-drawing your own whiskers is with coord_cartesian():

library(dotwhisker)
#> Loading required package: ggplot2

data(mtcars)
mtest <- lm(mpg ~ cyl + hp + wt, data = mtcars)
dwplot(mtest) + coord_cartesian(xlim = c(-4, 1))

Created on 2022-01-18 by the reprex package (v2.0.1)