peter5
peter5

Reputation: 13

R ggplot2 legend with linetypes

I am relatively new to R and I have some difficulties with ggplot2. I have a data frame consisting of three variables (alpha, beta, gamma) and I want to plot them together. I get the plot but I have two problems:

  1. legend is outside the plot and I want it to be inside
  2. linetypes are changed to "solid", "dashed" and "dotted"!

Any ideas/suggestions would be more than welcome!

p <- ggplot() + 
  geom_line(data=my.data,aes(x = time, y = alpha,linetype = 'dashed')) +
  geom_line(data=my.data,aes(x = time, y = beta, linetype = 'dotdash')) +
  geom_line(data=my.data,aes(x = time, y = gamma,linetype = 'twodash')) +
  scale_linetype_discrete(name = "", labels = c("alpha", "beta", "gamma"))+
  theme_bw()+
  xlab('time (years)')+
  ylab('Mean optimal paths')
print(p)

Upvotes: 1

Views: 428

Answers (1)

Vertho
Vertho

Reputation: 200

What you are after is easier to achieve if you first rearrange your data to long format, with one observation per row.

You can do this with tidyr's gather function. Then you can simply map the linetype to the variable in your data.

In your original approach, you tried to assign a literal 'linetype' by using aes(), but ggplot interprets this as you saying, 'assign a line type here as if the variable that is mapped to linetype had the value dashed/dotdash/twodash'. When drawing the plot, it looks up the linetypes in the default scale_linetype_discrete, the first three values of which happen to be solid, dotted and dashed, which is why you're seeing the confusing replacement. You can specify linetypes by using scale_linetype_manual.

The position of the legend is adjustable in theme(). legend.position = c(0,1) defines the legend to be placed at the left, top corner. legend.justification = c(0,1) sets the anchor to use in legend.position to the left, top corner of the legend box.

library(tidyr)
library(ggplot2)

# Create some example data
my.data <- data.frame(
    time=1:100,
    alpha = rnorm(100),
    beta = rnorm(100),
    gamma = rnorm(100)
)

my.data <- my.data %>%
    gather(key="variable", value="value", alpha, beta, gamma)

p <- ggplot(data=my.data, aes(x=time, y=value, linetype=variable)) + 
  geom_line() +
  scale_linetype_manual(
    values=c("solid", "dotdash", "twodash"), 
    name = "", 
    labels = c("alpha", "beta", "gamma")) +
  xlab('time (years)')+
  ylab('Mean optimal paths') +
  theme_bw() +
  theme(legend.position=c(0.1, 0.9), legend.justification=c(0,1))
print(p)

Upvotes: 2

Related Questions