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

时间:2016-05-03 13:51:34

标签: 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)

plot

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

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

2 个答案:

答案 0 :(得分: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))

enter image description here

答案 1 :(得分:3)

This Q&A帮助了我:你需要在颜色图例中明确指定形状,并使用' override.aes':

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"), 
                       guide = guide_legend(override.aes = list(shape = rep(c(1, 2), 2)))) +
  scale_linetype_discrete(name = "", 
                          breaks = c("1to1", "1to2", "2to1", "2to2"), 
                          labels = c("1to1", "1to2", "2to1", "2to2")) +
  scale_shape_discrete(guide = F)
plot1

enter image description here

但请注意,您需要自己确定正确的形状。 A reference might come handy.