尝试在ggplot中手动构建线型图例时出错

时间:2016-11-14 13:06:06

标签: r ggplot2 legend

我有一个包含两个不同变量y1y2的数据框:我想使用geom_line绘制两个变量,并使用两种不同的线型(color已被采用通过另一个变量)。我对使用meltgather的解决方案不感兴趣:我有充分的理由不想对我的真实数据这样做。相反,我正试图手工建立我的传奇:

library(ggplot2)

x <- rep(seq(0, 1, len = 10), times = 3 )
group <- gl(n = 3, k = 10, labels = c("A", "B", "C"))
foo <- data.frame(x = x, y1 = x^2, y2 = x^3, group = group)


p <- ggplot(data = foo, aes(x = x, color = group)) +
    geom_line(data = foo, aes(y = y1), linetype = "type1") +
    geom_line(data = foo, aes(y = y2), linetype = "type2") +
    guides(color = FALSE) +
    scale_linetype_manual(name = "variable",
                          values = c("type1" = "solid", "type2" = "dashed"),
                          labels = c("y1", "y2")) +
    facet_wrap( ~ group)
p

然而,ggplot给了我一个奇怪的错误:

> Error in grid.Call.graphics(L_lines, x$x, x$y, index, x$arrow) : 
  invalid line type: must be length 2, 4, 6 or 8

发生了什么事?你能救我吗?

1 个答案:

答案 0 :(得分:1)

您必须在linetype函数中使用aes

ggplot(data = foo, aes(x = x), color = group) +
  geom_line(data = foo, aes(y = y1, linetype = "type1")) +
  geom_line(data = foo, aes(y = y2, linetype = "type2")) + 
  guides(color = FALSE) +
  scale_linetype_manual(name = "variable",
                        values = c("type1" = "solid", "type2" = "dashed"),
                        labels = c("y1", "y2")) +
  facet_wrap( ~ group)

enter image description here