Delete legend elements of one specific geometry: "show.legend = FALSE" does not work

I wrote an answer here and would like to improve it. I would like to remove the legend for geom_path , but it does not work with show.legend = FALSE . The color geom_path remain in the legend ( Down and Up ). Am I doing something wrong?

Is there a way to manually tell ggplot just to show, let the last two elements of the legend say ( y2015 , y2016 )?

My code and output:

 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

+2
source share
2 answers

I think that happens because both variable and direction displayed in color, the legend has four different color values. Deleting a path legend simply removes the arrows, and deleting just a point legend deletes the points. But in any case, all four colors are still displayed in the legend as points or arrows, respectively, because the base display still has four values, regardless of whether you want to display these four values ​​as points, arrows, or both in the legend ,

One way is to use the aesthetics of the fill for glasses. Then the legend of the path will have only two meanings. To do this, you need to use a dot style with a filled interior (pch values ​​21-25). You will also need to change the colors of either the color aesthetics or fill the aesthetics so that they are not 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)) 

enter image description here

+2
source

Another possibility (but more general work) is to manually specify the colors for the arrows:

 library(ggplot2) library(tidyr) 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) ggplot2df %>% mutate(direction = ifelse(y2016 - y2015 > 0, "Up", "Down")) %>% gather(variable, value, -question, -direction) -> df gg <- ggplot(df, aes(x=question, y = value, group = question)) gg <- gg + geom_point(aes(color=variable), size=4) gg <- gg + geom_path(color=c("red", "red", "green", rep("red", 4), "green", "red", "red"), arrow=arrow(), show.legend=FALSE) gg 

enter image description here

+2
source

All Articles