删除一个特定几何图形的图例元素:"show.legend = FALSE";不胜任 [英] Remove legend elements of one specific geom: "show.legend = FALSE" does not do the job

查看:434
本文介绍了删除一个特定几何图形的图例元素:"show.legend = FALSE";不胜任的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写了一个答案这里,并希望对其进行改进. 我想做的是删除geom_path的图例,但它不适用于show.legend = FALSE. geom_pathcolor元素保留在图例中(DownUp).我在做错什么吗?

I have written an answer here and would like to improve it. What I would like to do is to remove the legend for geom_path but it is not working with show.legend = FALSE. The color elements of geom_path remain in the legend (Down and Up). Am I doing something wrong?

是否还有一种方法可以手动告诉ggplot只是为了让我们说说图例的最后两个元素(y2015y2016)?

Is there alternatively a way to manually tell ggplot just to show lets say the last two elements of the legend (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)  

推荐答案

我认为这是因为variabledirection都被映射为颜色,因此图例具有四个不同的颜色值.删除路径图例只会删除箭头,而仅删除点图例也会删除点.但是,无论哪种方式,所有四种颜色仍分别在图例中显示为点或箭头,这是因为基础映射仍具有四个值,无论您选择在图例中将这四个值显示为点,箭头还是两者都显示. .

I think what's going on is that because both variable and direction are mapped to color, the legend has four different color values. Removing the path legend just removes the arrows, while removing just the point legend removes the points. But either way, all four colors still show up in the legend, as points or arrows, respectively, because the underlying mapping still has four values, regardless of whether you choose to manifest those four values as points, arrows, or both in the legend.

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

One way around this would be to use a fill aesthetic for the points. Then the path legend will have only two values. To do this, you have to use a point style with a filled interior (pch values 21 - 25). You'll also need to change the colors of either the color aesthetic or fill aesthetic, so that they won't be the same:

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))

这篇关于删除一个特定几何图形的图例元素:"show.legend = FALSE";不胜任的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆