ggplot使用facet_grid时如何让geom_rect的透明度保持一致
问题成因
你当前的写法中geom_rect继承了全局的数据集映射,每个分面内有多少条数据,对应的矩形就会被重复绘制多少次:叠加的层数越多,实际显示的颜色就越深(透明度越低),不同分面的数据量不同,最终就出现了透明度不一致的问题。
解决方法
方法1:使用annotate绘制背景(推荐)
annotate不会和数据集绑定,每个分面仅绘制一次矩形,透明度可以保持完全统一,修改后的代码如下:
ggplot(df, aes(x=Dem) )+ theme_bw()+ # 正区间背景 annotate("rect", ymin = 0, ymax = 0.2, xmin = -Inf, xmax = Inf, fill = 'negligible', alpha = .2)+ annotate("rect", ymin = 0.2, ymax = 0.5, xmin = -Inf, xmax = Inf, fill = 'small', alpha = .2)+ annotate("rect", ymin = 0.5, ymax = 0.8, xmin = -Inf, xmax = Inf, fill = 'medium', alpha = .2)+ annotate("rect", ymin = 0.8, ymax = Inf, xmin = -Inf, xmax = Inf, fill = 'large', alpha = .2)+ # 负区间背景 annotate("rect", ymin = 0, ymax = -0.2, xmin = -Inf, xmax = Inf, fill = 'negligible', alpha = .2)+ annotate("rect", ymin = -0.2, ymax = -0.5, xmin = -Inf, xmax = Inf, fill = 'small', alpha = .2)+ annotate("rect", ymin = -0.5, ymax = -0.8, xmin = -Inf, xmax = Inf, fill = 'medium', alpha = .2)+ annotate("rect", ymin = -0.8, ymax = -Inf, xmin = -Inf, xmax = Inf, fill = 'large', alpha = .2)+ # 原有数据图层 geom_point(aes(y=effect), stat="identity")+ geom_errorbar(aes(ymin=lower, ymax=upper), width=.2)+ facet_grid(Subject~cat, scales="free")+ theme(axis.text.x = element_text(angle = 45, hjust = 1))
方法2:单独绑定空数据框保留图例
如果需要保留填充色的分类图例,可以单独创建一个空数据框给geom_rect使用,避免重复绘制:
# 创建空的背景映射数据框,不会触发重复绘制 bg_data <- data.frame() ggplot(df, aes(x=Dem) )+ theme_bw()+ # 正区间背景,关闭全局美学继承 geom_rect(data = bg_data, aes(ymin = 0, ymax = 0.2, xmin = -Inf, xmax = Inf, fill = 'negligible'), alpha = .2, inherit.aes = FALSE)+ geom_rect(data = bg_data, aes(ymin = 0.2, ymax = 0.5, xmin = -Inf, xmax = Inf, fill = 'small'), alpha = .2, inherit.aes = FALSE)+ geom_rect(data = bg_data, aes(ymin = 0.5, ymax = 0.8, xmin = -Inf, xmax = Inf, fill = 'medium'), alpha = .2, inherit.aes = FALSE)+ geom_rect(data = bg_data, aes(ymin = 0.8, ymax = Inf, xmin = -Inf, xmax = Inf, fill = 'large'), alpha = .2, inherit.aes = FALSE)+ # 负区间背景 geom_rect(data = bg_data, aes(ymin = 0, ymax = -0.2, xmin = -Inf, xmax = Inf, fill = 'negligible'), alpha = .2, inherit.aes = FALSE)+ geom_rect(data = bg_data, aes(ymin = -0.2, ymax = -0.5, xmin = -Inf, xmax = Inf, fill = 'small'), alpha = .2, inherit.aes = FALSE)+ geom_rect(data = bg_data, aes(ymin = -0.5, ymax = -0.8, xmin = -Inf, xmax = Inf, fill = 'medium'), alpha = .2, inherit.aes = FALSE)+ geom_rect(data = bg_data, aes(ymin = -0.8, ymax = -Inf, xmin = -Inf, xmax = Inf, fill = 'large'), alpha = .2, inherit.aes = FALSE)+ # 原有数据图层 geom_point(aes(y=effect), stat="identity")+ geom_errorbar(aes(ymin=lower, ymax=upper), width=.2)+ facet_grid(Subject~cat, scales="free")+ theme(axis.text.x = element_text(angle = 45, hjust = 1))
内容的提问来源于stack exchange,提问作者yuliaUU
相关产品推荐
相关产品推荐

