2

I have a data set that uses both the line type and color aesthetic. The legend shows both aesthetics but I would only like one aesthetic (either color or line type) in the legend itself.

This also applies to another data set in which I want only one out of four lines larger than the rest which I do with an ifelse statement in the geom_line aesthetic, but the actual ifelse statement shows up in the legend.

I've taken an example from the mtcars data set where I want only color to show up.

library(tidyverse)
mtcars <- as.tibble(mtcars)

mtcars$gear <- as.factor(mtcars$gear)
mtcars$cyl <- as.factor(mtcars$cyl)

mtcars1 <- mtcars %>%
  arrange(gear) %>%
  ggplot(aes(x = qsec, group = 1)) +
  geom_point(aes(y=disp, group = cyl, color = cyl)) +
  geom_line(aes(y=disp, group = cyl, color = cyl, linetype = cyl)) + 
  scale_color_manual(values=c("#000000", "#E69F00", "#56B4E9")) + 
  labs(title = "MTCARS Example", colour="Cylinder",x= "x",y="Disp") 
print(mtcars1)

Is it possible to manipulate the legend to only show one aesthetic?

pogibas
  • 27,303
  • 19
  • 84
  • 117
Jordan
  • 1,415
  • 3
  • 18
  • 44

2 Answers2

3

Try

mtcars1 + guides(color = "none")
mtcars1 + guides(linetype = "none")
Pierre
  • 671
  • 8
  • 25
1

Short answer: use same legend name: labs(colour = "Cylinder", linetype = "Cylinder).

# Simplified version of the same plot
library(ggplot2)
# 1. All aes specified in main ggplot2 function
# 2. In aes x always goes first, y always goes second,
#    you don't need to write x = ..., y = ...
ggplot(mtcars, aes(qsec, disp, color = cyl, linetype = cyl)) +
    geom_point() +
    geom_line() +
    scale_color_manual(values = c("#000000", "#E69F00", "#56B4E9")) + 
    # For "tidier" code use same order as in aes 
    # (except for main title, or subtitle)
    labs(title = "MTCARS Example", 
         x = "x",
         y = "Disp", 
         color = "Cylinder", 
         linetype = "Cylinder")

If you want to use combined legends you have to use same variables for aes (you're already doing that). By default legend name would be cyl. But when you change name for a single aesthetics (color = "Cylinder") ggplot2 thinks that you're using two different variables. Thus you have to rename both aesthetics for a plot like this:

enter image description here

PS.: I simplified your ggplot2 function. Don't rewrite y=disp, color = cyl multiple times, set them in main ggplot2 function. Also, you don't need group (have know idea what you tried to do there).

pogibas
  • 27,303
  • 19
  • 84
  • 117
  • Thanks @PoGibas. I read some where I needed it. (I'm newish to R) Why would someone use `group`? – Jordan Apr 12 '18 at 12:26
  • 1
    @Jordan Take a look at this [question](https://stackoverflow.com/questions/10357768/plotting-lines-and-the-group-aesthetic-in-ggplot2) (tl;dr use it for factors). Also, you **don't** need `print` to show plot, just type `mtcars1`. – pogibas Apr 12 '18 at 12:30