删除一个特定几何图形的图例元素:“show.legend = FALSE”不起作用

2023-11-29

我已经写了一个答案here并想改进它。 我想做的是删除图例geom_path但它不与show.legend = FALSE. The color要点geom_path留在传说中(Down and Up)。难道我做错了什么?

有没有办法手动告诉ggplot只是为了展示让我们说图例的最后两个元素(y2015, y2016)?

我的代码和输出:

library(ggplot2)
library(reshape2)
library(dplyr)

ggplot2df <- read.table(text = "question y2015 y2016
                        q1 90 50
                        q2 80 60
                        q3 70 90
                        q4 90 60
                        q5 30 20", header = TRUE)


df <- ggplot2df %>% 
  mutate(direction = ifelse(y2016 - y2015 > 0, "Up", "Down"))%>%
  melt(id = c("question", "direction"))


ggplot(df, aes(x=question, y = value, color = variable, group = question )) + 
geom_point(size=4) + 
geom_path(aes(color = direction), arrow=arrow(), show.legend = FALSE)  

enter image description here


我认为正在发生的事情是因为两者variable and direction映射到颜色,图例有四种不同的颜色值。删除路径图例只会删除箭头,而仅删除点图例则会删除点。但无论哪种方式,所有四种颜色仍然分别显示在图例中,作为点或箭头,因为底层映射仍然具有四个值,无论您选择将这四个值显示为图例中的点、箭头还是两者都显示。

解决这个问题的一种方法是对点使用填充美学。那么路径图例将只有两个值。为此,您必须使用具有填充内部的点样式(pch 值 21 - 25)。您还需要更改颜色美感或填充美感的颜色,以便它们不会相同:

ggplot(df, aes(x=question, y = value, group = question)) + 
  geom_point(size=4, aes(fill=variable), pch=21, color=NA) + 
  geom_path(aes(color = direction), arrow=arrow(), show.legend=FALSE) +
  scale_fill_manual(values=hcl(c(105,285), 100, 50))

enter image description here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

删除一个特定几何图形的图例元素:“show.legend = FALSE”不起作用 的相关文章

随机推荐