R ggplot使用facet_wrap时如何给指定分面修改背景色实现高亮
实现方法
theme()为全局样式控制函数,无法直接映射分面变量值单独修改指定分面样式,可通过新增背景图层的方式实现需求,无需额外安装扩展包,具体操作如下:
- 构造高亮分面的数据集,仅需指定需要高亮的
topicr取值:
highlight_bg <- data.frame( topicr = c(37, 42) )
- 将背景图层放在所有绘图图层的最前端,保证后续的线、点等元素显示在背景上方,修改后的完整代码如下:
library(ggplot2) library(scales) axr_treat_ctrl %>% ggplot(aes(x= year, y= mtopic,colour= Type,group=Type))+ # 新增高亮背景层,inherit.aes=FALSE避免继承全局映射参数 geom_rect(data = highlight_bg, aes(xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf), fill = "lightblue", alpha = 0.3, inherit.aes = FALSE)+ geom_line( )+ geom_point(size = 1) + scale_y_continuous(breaks = extended_breaks(n = 5))+ scale_x_continuous(breaks = extended_breaks(n = 10))+ geom_vline(xintercept = 2005, linetype=2, color= "brown")+ geom_vline(xintercept = c(2010,2011,2017), linetype=3, color= "blue")+ labs(x = "x-axis", y = "y-axis")+ facet_wrap(~topicr)+ guides(x = guide_axis(angle = 90))+ theme(legend.position = "bottom")
如果需要更精细的面板样式控制,也可以使用ggh4x扩展包的facet_wrap2()函数,直接按分面指定面板背景:
library(ggplot2) library(scales) library(ggh4x) axr_treat_ctrl %>% ggplot(aes(x= year, y= mtopic,colour= Type,group=Type))+ geom_line( )+ geom_point(size = 1) + scale_y_continuous(breaks = extended_breaks(n = 5))+ scale_x_continuous(breaks = extended_breaks(n = 10))+ geom_vline(xintercept = 2005, linetype=2, color= "brown")+ geom_vline(xintercept = c(2010,2011,2017), linetype=3, color= "blue")+ labs(x = "x-axis", y = "y-axis")+ facet_wrap2(~topicr, theme = theme( panel.background = element_rect(fill = ifelse( as.numeric(levels(factor(topicr)))[.x] %in% c(37,42), "lightblue", "white" )) ))+ guides(x = guide_axis(angle = 90))+ theme(legend.position = "bottom")
内容的提问来源于stack exchange,提问作者Jian Zhang
相关产品推荐
相关产品推荐

