9
votes

I would like to adjust the linetypes in the following ggplot. I thus introduce another column in the data.frame df to represent the line type, but once I convert it to a factor the linetype instead of "method" appears in the legend... (see trial 3).

How can I get "method" in the legend? In the end I would like to be able to

  1. freely choose the linetype,
  2. freely choose the order in which these linetypes appear in the legend, and
  3. have the corresponding "method" shown as legend text.

Here are my attempts:

require(ggplot2)
set.seed(1)
df <- data.frame(x=c(1:4, 2:5),
                 method=rep(c("a", "b"), each=4),
                 lt=rep(c(5,3), each=4),
                 value=rep(c(0,1), each=4)+runif(8))

## trial 1:
ggplot(df, aes(x=x, y=value)) + 
   geom_point() + 
   geom_line(aes(group=method, linetype=method)) 
# fine, but not the linetypes I would like to have

## trial 2:
ggplot(df, aes(x=x, y=value)) + 
   geom_point() + 
   geom_line(aes(group=method, linetype=lt)) 
# correct linetypes, but no legend

## trial 3:
ggplot(df, aes(x=x, y=value)) + 
   geom_point() + 
   geom_line(aes(group=method, linetype=as.factor(lt))) 
# legend, but not the correct one (I would like to have the "group"ing 
# variable "method" in the legend as in trial 1)
1
+ scale_linetype(name = "Method") seems to work with trial 3.Chase
That gives me the legend title "Method", but still I get "3" and "5" as legend texts instead of "a" and "b" as in trial 1Marius Hofert

1 Answers

17
votes

Use method as the linetype, but then manually map it to the types of lines you want. You don't need to introduce another variable this way.

ggplot(df, aes(x=x, y=value)) +
    geom_point() +
    geom_line(aes(linetype=method)) +
    scale_linetype_manual(breaks=c("a","b"), values=c(5,3))

enter image description here