Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: how to adjust line types + order in legend?

Tags:

r

ggplot2

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)
like image 841
Marius Hofert Avatar asked Dec 06 '11 21:12

Marius Hofert


1 Answers

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

like image 93
Brian Diggs Avatar answered Oct 19 '22 13:10

Brian Diggs