ggplot2:有两个映射的一个图例

mts*_*mts 3 r ggplot2

我正在做一个有两个不同映射的绘图("group"映射到颜色和linetype,"to"映射到shape).我想将这两个映射组合在一个图例中,但无法在图例中获得正确的形状.
这是我的尝试:

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)
Run Code Online (Sandbox Code Playgroud)

情节

正如你在情节中看到的,我有一个传说,但形状总是一个圆圈.
期望的行为:图例中的形状在圆和金字塔之间交替,如图中所示.

到目前为止我尝试过的是手动指定形状但是没有帮助,如上所示.我也看了我的情节对象,希望能够操纵它,但无济于事.

eip*_*i10 5

没有你可以得到一个传奇override.aes.只要设定shape=group为好,用scale_shape_manual设置重复形状值.在这种情况下,您不需要映射to到任何内容,因为它包含的信息是多余的:

ggplot(plotdata, aes(x = x, y = y, group = group, color = group, lty = group, 
                     shape = group)) +
  geom_point() + geom_line() + theme_bw() + 
  scale_color_discrete(name = "") +
  scale_linetype_discrete(name = "") +
  scale_shape_manual(name = "", values=c(1,2,1,2))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述