如何为ggplot2中facet_wrap的分面标题栏添加灰色粗边框?
问题描述
需要给ggplot2中facet_wrap生成的分面标题栏(strip)添加与目标图一致的灰色粗边框。现有绘图效果、目标效果及当前代码如下:
当前绘图

目标绘图

当前代码
ggplot(data = melted_df, aes(sample = value, color = Distribution)) + stat_qq() + geom_qq_line() + facet_wrap(~Distribution, scales = "free") + xlab('Theoretical Quantiles') + ylab('Sample Quantiles') + ggtitle('QQ Plot for Different Distributions against Qnorm!') + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), plot.title = element_text(size = 11), panel.background = element_rect(fill = "white"), legend.background=element_rect(fill = "lightgray"), legend.key = element_rect(fill = "lightgray"), axis.ticks.x = element_blank(), axis.ticks.y = element_blank(), legend.box.background = element_rect(color = "gray45", fill = NA, size=3), panel.border = element_rect(color = "gray45",fill = NA, size = 2), strip.text = element_text(size = 10))
解决方案
要实现目标效果,只需在theme()中添加分面标题栏的背景和边框设置即可,关键是配置strip.background和strip.border两个参数:
修改后的完整代码:
ggplot(data = melted_df, aes(sample = value, color = Distribution)) + stat_qq() + geom_qq_line() + facet_wrap(~Distribution, scales = "free") + xlab('理论分位数') + ylab('样本分位数') + ggtitle('不同分布与正态分布的QQ图') + theme( panel.grid.major = element_blank(), panel.grid.minor = element_blank(), plot.title = element_text(size = 11), panel.background = element_rect(fill = "white"), legend.background = element_rect(fill = "lightgray"), legend.key = element_rect(fill = "lightgray"), axis.ticks.x = element_blank(), axis.ticks.y = element_blank(), legend.box.background = element_rect(color = "gray45", fill = NA, size=3), panel.border = element_rect(color = "gray45", fill = NA, size = 2), strip.text = element_text(size = 10), # 新增分面标题栏样式设置 strip.background = element_rect(fill = "lightgray"), # 匹配目标图的浅灰背景 strip.border = element_rect(color = "gray45", fill = NA, size = 2) # 灰色粗边框 )
参数说明
strip.border:指定边框颜色为gray45(与现有面板边框颜色统一),fill=NA避免覆盖背景,size=2保证边框粗细和面板一致strip.background:给标题栏设置浅灰色背景,完全匹配目标图的视觉效果,如果不需要背景可删除该行
内容的提问来源于stack exchange,提问作者qqplotter
相关产品推荐
相关产品推荐

