r - Want single legend when plotting multiple datasets and using ggnewscale - Stack Overflow

I want to plot a dataset and then overlay a subset of the dataset in grey. I am using ggnewscale to col

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

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
Share Improve this question edited Mar 22 at 0:07 jpsmith 17.9k6 gold badges23 silver badges45 bronze badges asked Mar 21 at 20:32 user17213841user17213841 515 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744334583a4569051.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信