DeltaIV DeltaIV - 20 days ago 7
R Question

Error when trying to build linetype legend manually in ggplot

I have a dataframe with two different variables

y1
and
y2
: I want to plot both of them using
geom_line
, with two different linetypes (
color
is already taken by another variable). I'm not interested in solutions using
melt
or
gather
: I have good reasons for not wanting to do that with my real data. Instead, I'm trying to build my legend by hand:

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


However,
ggplot
is giving me a weird error:

> 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


What's happening? Can you help me?

J_F J_F
Answer

You have to use linetype in your aes function:

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

Comments