如何移除ggplot2中geom_rect的绿色轮廓线?
移除ggplot2中geom_rect的轮廓线问题
问题描述
使用ggplot2绘制图表时,geom_rect元素出现绿色边框,尝试在aes()中设置color=NA未解决问题,如何移除该轮廓线?
问题原因
代码在ggplot()的全局美学映射(aes())中绑定了color到domain变量,geom_rect会继承这个全局的color属性。之前在aes()里设置color=NA无效,是因为这属于映射设置,而非直接指定元素的颜色属性,无法覆盖全局的color映射。
解决方案
提供两种可行方法:
方法一:将color映射移到需要的geom中
把全局aes()里的color和Group移到geom_errorbar和geom_point的aes()中,让geom_rect不继承全局颜色映射:
library(ggplot2) library(tidyverse) mydat <- data.frame(mean = c(23, 24, 15, 27, 18, 19, 23, 20, 32), lower = c(20, 19, 13, 15, 14, 18, 20, 17, 20), upper = c(25, 29, 17, 39, 22, 20, 26, 23, 40), class = c("A", "B", "C", "A", "B", "C", "A", "B", "C"), domain = c("North", "North", "North", "West", "West", "West", "South", "South", "South"), stripe = c(1, 0, 1, 1, 0, 1, 1, 0, 1)) mydat$class <- as.factor(mydat$class) mydat$domain <- as.factor(mydat$domain) mydat$stripe <- as.factor(mydat$stripe) colour_palette <- scales::hue_pal()(3) p <- mydat %>% ggplot(aes(x = mean, y = fct_reorder(.f = class, .x = upper, .fun = max), xmin = lower, xmax = upper)) + # 移除全局的color和Group映射 geom_errorbar(aes(color = fct_reorder(.f = domain, .x = upper, .fun = max), Group = fct_reorder(.f = domain, .x = upper, .fun = max)), width = 0.1, position = position_dodge(width = 0.5)) + geom_rect(aes(ymin = 0.5, ymax = 1.5, xmin = -Inf, xmax = Inf, fill = stripe), alpha = 0.1) + geom_rect(aes(ymin = 2.5, ymax = 3.5, xmin = -Inf, xmax = Inf, fill = stripe), alpha = 0.1) + scale_fill_manual(values = c("grey", "transparent")) + theme_light(base_size = 18) + geom_point(aes(color = fct_reorder(.f = domain, .x = upper, .fun = max), Group = fct_reorder(.f = domain, .x = upper, .fun = max)), position = position_dodge(width = 0.5)) + xlab("") + ylab("") + scale_color_manual(values = c("North" = colour_palette[1], "South" = colour_palette[2], "West" = colour_palette[3]), name = "Domain") + guides(fill = "none") p
方法二:给geom_rect显式设置color=NA
直接在geom_rect的参数中(而非aes()内部)设置color=NA,覆盖全局颜色映射:
修改原代码中的geom_rect部分为:
geom_rect(aes(ymin = 0.5, ymax = 1.5, xmin = -Inf, xmax = Inf, fill = stripe), alpha = 0.1, color = NA) + geom_rect(aes(ymin = 2.5, ymax = 3.5, xmin = -Inf, xmax = Inf, fill = stripe), alpha = 0.1, color = NA) +
内容的提问来源于stack exchange,提问作者Adrian
相关产品推荐
相关产品推荐

