我有一个包含两个不同变量y1
和y2
的数据框:我想使用geom_line
绘制两个变量,并使用两种不同的线型(color
已被采用通过另一个变量)。我对使用melt
或gather
的解决方案不感兴趣:我有充分的理由不想对我的真实数据这样做。相反,我正试图手工建立我的传奇:
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
发生了什么事?你能救我吗?
答案 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)