如何缩小plot_summs绘图内元素间距,使两个系数更靠近?
缩小plot_summs绘图空白区域的方法
要让两个系数更贴近,核心是减少绘图的垂直空白空间,可通过以下几种方式实现:
方法1:调整y轴的扩展间距
plot_summs基于ggplot2,可通过scale_y_discrete()的expand参数减少y轴上下的空白padding:
library(jtools) library(ggplot2) states <- as.data.frame(state.x77) fit1 <- lm(Income ~ Frost + Illiteracy + Murder + Population + Area + `Life Exp` + `HS Grad`, data = states, weights = runif(50, 0.1, 3)) p <- plot_summs(fit1, coefs = c("Frost Days" = "Frost", "% Illiterate" = "Illiteracy"), scale = TRUE) p + geom_text(aes(label = round(estimate)), vjust=-1)+ theme(legend.position = "none") + # 减少y轴上下的空白比例,mult值越小空白越少 scale_y_discrete(expand = expansion(mult = c(0.02, 0.02)))
方法2:缩小绘图整体边距
通过theme()的plot.margin参数减少绘图四周的空白,重点缩小上下边距:
p + geom_text(aes(label = round(estimate)), vjust=-1)+ theme( legend.position = "none", # 调整上下边距(单位:points,顺序为上、右、下、左) plot.margin = margin(5, 10, 5, 10) ) + scale_y_discrete(expand = expansion(mult = c(0.02, 0.02)))
方法3:调整绘图保存尺寸
保存时设置更小的高度,让垂直空间更紧凑:
ggsave("compact_plot.jpg", plot = p, height = 2, width = 5, dpi = 300)
以上方法结合使用,能有效让两个系数的条形图彼此更贴近,减少不必要的空白区域。
内容的提问来源于stack exchange,提问作者m45ha
相关产品推荐
相关产品推荐

