在直方图上叠加分组密度曲线:如何移除图例中的密度标记?(ggplot2, R)
解决ggplot图例方块的蓝色粗边框问题
直接给geom_density()加上show.legend = FALSE参数就能解决这个问题,修改后的完整代码如下:
require(ggplot2) mtcars$am2 <- factor(mtcars$am) p1 <- ggplot(mtcars, aes(x = mpg, y = ..density.., fill = am2)) + geom_histogram(position = "identity", alpha = 0.8, colour = 1, bins = 12)+ scale_fill_manual(values = c( "pink", "lightgrey")) + theme( legend.position = "bottom" ) p1 + geom_density(colour = "blue", lwd = 2, inherit.aes = F, aes(x = mpg, y = ..density.., group = am2), show.legend = FALSE) # 新增参数阻止该图层影响图例
原因说明
你之前的代码里,geom_density指定了group = am2,即便设置了inherit.aes = FALSE,ggplot依然会把这个图层的视觉元素(蓝色粗线)加入到图例的方块边框里。加上show.legend = FALSE后,这个图层就不会参与图例的构建,图例只会保留对应直方图填充色的方块,蓝色边框自然就消失了。
内容的提问来源于stack exchange,提问作者Reader 123
相关产品推荐
相关产品推荐

