I am doing a plot with two different mappings ("group" is mapped to color and linetype and "to" is mapped to shape). I would like to combine those two mappings in a single legend but can't get the shape right in the legend.
Here's my try:
set.seed(123)
plotdata = cbind.data.frame(x = rep(1:5, times = 4),
y = rnorm(20),
from = rep(c("1","2"), each = 10),
to = rep(c("1","2"), times= 10))
plotdata = cbind.data.frame(plotdata, group = paste0(plotdata$from, "to", plotdata$to))
library(ggplot2)
plot1 = ggplot(plotdata, aes(x = x, y = y, group = group, color = group, lty = group, shape = to)) +
geom_point() + geom_line() + theme_bw() +
scale_color_discrete(name = "",
breaks = c("1to1", "1to2", "2to1", "2to2"),
labels = c("1to1", "1to2", "2to1", "2to2")) +
scale_linetype_discrete(name = "",
breaks = c("1to1", "1to2", "2to1", "2to2"),
labels = c("1to1", "1to2", "2to1", "2to2")) +
scale_shape_manual(name = "",
values = c(1, 2, 1, 2),
breaks = c("1to1", "1to2", "2to1", "2to2"),
labels = c("1to1", "1to2", "2to1", "2to2"))
print(plot1)
As you can see in the plot I have one legend but the shape is always a circle.
Desired behaviour: shape in the legend alternates between circle and pyramid as in the plot.
What I have tried so far was to specify the shape manually but that did not help as you can see above. I also looked at my plot object hoping to be able to manipulate it but to no avail.