rggplot2legendggnewscale

Want single legend when plotting multiple datasets and using ggnewscale


I want to plot a dataset and then overlay a subset of the dataset in grey. I am using ggnewscale to colour the subset differently. The plot is as desired but I would like to remove the legend with grey curves.

library(ggplot)
library(dplyr)
library(ggnewscale)
x <- 1:20
W <- c(1, 2)

df <- expand.grid(x = x, W = W)
df <- df %>% mutate(y = W * x, W = as.factor(W))
df2 <- df %>% filter(y < 15)

p <- df %>%
  ggplot(aes(x, y, colour = W, linetype = W)) +
  geom_point(size = 2) +
  geom_line(linewidth = 1) +
  labs(colour = "W", linetype = "W") +

  new_scale_colour() +

  geom_point(data = df2, aes(x, y, colour = W), size = 2) +
  geom_line(data = df2, aes(x, y, colour = W), linetype = "solid", linewidth = 2) +
  scale_colour_manual(values = c("grey", "grey")) 
p

Solution

  • I don't see any reason why we need ggnewscale to achieve your desired result. Instead you can simply set the "grey" color as a parameter (and map W on the group aes in the second geom_line):

    library(ggplot2)
    library(dplyr, warn = FALSE)
    
    p <- df %>%
      ggplot(aes(x, y, colour = W, linetype = W)) +
      geom_point(size = 2) +
      geom_line(linewidth = 1) +
      labs(colour = "W", linetype = "W") +
      geom_point(data = df2, aes(x, y), size = 2, color = "grey") +
      geom_line(
        data = df2, aes(x, y, group = W),
        linetype = "solid", linewidth = 2, color = "grey"
      )
    
    p