2

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

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.