london london - 3 months ago 19
R Question

ggplot2, how to control for linetype and colour

I have four time series variables, I want to plot them all in one graph. I want to plot two variables in solid line and the other tow in dashed line. The solid lines will be in red and blue, the dashed lines will be in black and brown. I was wondering if anyone could help with coding? I've the following for now:

data1 = melt(data, id = 'Year')
ggplot(data1, aes(x = Year, y = value,colour=variable)) +
geom_line() +
ylab(label="Index") + xlab("") +
scale_colour_manual(values = c("red","blue","black", "brown"),labels = c("ES","LS","Wax","EP"))+
theme(legend.position=c(0.15,0.85),legend.title=element_blank(),legend.background = element_rect(fill=NULL))


This code produced a graph with solid lines only.

Answer

I assumed I could recreate something that looks alike data1 with this

data1=data.frame(Year=1:100,value=rnorm(100),variable=factor(floor(4*runif(100)+1)))

What you need to change your linetype is the scale_linetype_manual() function.

For instance in your problem, my answer would be

library(ggplot2)
ggplot(data1, aes(x = Year, y = value,colour=variable)) + 
  geom_line(aes(linetype=variable)) +
  ylab(label="Index") + xlab("") +
  scale_linetype_manual(values=c("solid", "solid","dashed", "dashed"),labels=c("ES","LS","Wax","EP")) +
  scale_colour_manual(values = c("red","blue","black", "brown"),labels=c("ES","LS","Wax","EP"))+
  theme(legend.position=c(0.15,0.85),legend.title=element_blank(),legend.background = element_rect(fill=NULL))

Which produces : Graph with legend

Comments