jester
jester

Reputation: 309

change line type in ggplot2 in r

I have a data frame like this.

 df <- data.frame(date = c('2015-11-23','2015-11-24','2015-11-25','2015-11-23','2015-11-24','2015-11-25'),
          variable = c('LCNB', 'LCNB','LCNB','LCDEF','LCDEF','LCDEF'),
          value = c(1,2,3,3,2,1))

I want to plot two lines in the same plot, with different color and line types. my current code is:

library(scales)
ggplot(df, aes(x=as.Date(date), y=value, color=variable)) + geom_line(size=1.07) + 
scale_color_manual(labels = c("Nb",'Def'), values = c("#E69F00", "#0072B2"))   +
scale_x_date(labels = date_format("%Y-%m-%d"), breaks = date_breaks("2.8 month")) +
theme(axis.text.x = element_text(angle = 0, vjust = 0.5,   hjust=1))+labs(x="Dates",y="%") + 
theme_bw()+
 theme( panel.grid.major = element_blank(),panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"),plot.margin=unit(c(0,1,0.3,1), "cm")) +
labs(colour = "LC") + theme(legend.position = c(0.95,0.85))

my code so far only makes two lines different color, how can i make them differnt line types as well.

Thank you for the help,

Upvotes: 0

Views: 62

Answers (1)

Melissa Key
Melissa Key

Reputation: 4551

You just need to take the same steps with line type as you did with color, but for linetype:

ggplot(df, aes(x=date, y=value, color=variable, linetype = variable)) + 
  geom_line(size=1.07,) + 
  scale_color_manual(
    labels = c("Nb",'Def'),
    values = c("#E69F00", "#0072B2")
  )   +
  scale_linetype(labels = c("Nb", "Def")) + 
  scale_x_date(labels = date_format("%Y-%m-%d"), breaks = date_breaks("2.8 month")) +
  theme(axis.text.x = element_text(angle = 0, vjust = 0.5,   hjust=1)) +
  labs(x="Dates",y="%", colour = "LC", linetype = "LC") + 
  theme_bw()+
  theme(
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    axis.line = element_line(colour = "black"),
    plot.margin=unit(c(0,1,0.3,1), "cm"),
    legend.position = c(0.95,0.85))

Upvotes: 2

Related Questions