Reputation: 51
I am trying to create a plot for three groups using three different coloured lines but only two of the groups have point markers. I can get the plot to display correctly but the legend shows the same point markers for all three groups.
I have created a reproducible example using the mpg dataset
library(tidyverse)
ggplot(mpg) +
geom_line(mapping = aes(x = displ, y = cty, color = drv), size = 1) +
geom_point(data = subset(mpg, drv != '4'), mapping = aes(x = displ, y = cty, color = drv, shape = drv), size = 3) +
scale_color_manual(name="Variable", labels = c("4", "f", "r"), values=c("4" = "#DA2128", "f" = "black", "r" = "blue")) +
scale_shape_manual(name="Variable", labels = c("f", "r"), values = c("f" = 16, "r" = 17), guide = FALSE)
The group '4' should have no point marker in the legend and the group 'r' should show a triangle marker
Thanks in advance for your help
Upvotes: 1
Views: 1511
Reputation: 17648
Try some alpha
ggplot(mpg, aes(x = displ, y = cty, color = drv, shape = drv)) +
geom_line() +
geom_point(aes(alpha=drv), size = 3) +
scale_alpha_manual(values = c(0,1,1)) +
scale_shape_manual(values = c(1,16, 17))
Or simply set shape 4
to NA
ggplot(mpg, aes(x = displ, y = cty, color = drv, shape = drv)) +
geom_line() +
geom_point(size = 3) +
scale_shape_manual(values = c(NA, 16, 17)) +
scale_color_manual(values = c("#DA2128", "black", "blue"))
Upvotes: 1
Reputation: 602
You could also disable the legend for shape
and set the values for shape
manually in the color
legend:
ggplot(mpg) +
geom_line(mapping = aes(x = displ, y = cty, color = drv), size = 1) +
geom_point(data = subset(mpg, drv != '4'), mapping = aes(x = displ, y = cty, color = drv, shape = drv), size = 3) +
scale_color_manual(name="Variable", labels = c("4", "f", "r"), values=c("4" = "#DA2128", "f" = "black", "r" = "blue"), guide=guide_legend(override.aes = list(shape = c("4" = NA, "f" = 16, "r" = 17)))) +
scale_shape_manual(values = c("f" = 16, "r" = 17), guide=F)
Upvotes: 0
Reputation: 903
Adding linetype
argument in your geom_line()
with the variable of interest (drv
in this case) gives your expected result.
library(tidyverse)
ggplot(mpg) +
geom_line(mapping = aes(x = displ, y = cty, color = drv, linetype = drv), size = 1) +
geom_point(data = subset(mpg, drv != '4'), mapping = aes(x = displ, y = cty, color = drv, shape = drv), size = 3) +
scale_color_manual(name="Variable", labels = c("4", "f", "r"), values=c("4" = "#DA2128", "f" = "black", "r" = "blue")) +
scale_shape_manual(name="Variable", labels = c("f", "r"), values = c("f" = 16, "r" = 17), guide = FALSE)
Upvotes: 0