1
votes

I have two time series data that I want to show on the same graph. Both series have three columns: Date, County and Value. Here is my code:

#Data
Series1 <- data.frame(Date = c(2000,2001,2000,2001), County = c("a", "a", "b", "b"),Total = c(100,150,190,130))
Series2 <- data.frame(Date = c(2000,2001,2000,2001), County = c("a", "a", "b", "b"),Total = c(180,120,140,120))

#Plot data
ggplot() + 
    geom_line(data = Series1, aes(x = Date, y = Total, color = County), linetype="solid") +
    geom_line(data = Series2, aes(x = Date, y = Total, color = County), linetype="dashed")

The plot looks like this:

plot

Now I just need to add one legend showing that solid line represents Series1 and dashed line represents Series2. How can I do this?

2
@PereG I tried +scale_linetype_manual("Type",values=c("solid"=2,"dashed"=1)), but nothing happen. - Sean
@Sean if you provide a minimum reproducible example, it would be much easier to help - PereG
@PereG I added a small subset of my data as example, hope it will help. TIA. - Sean

2 Answers

1
votes

Legends are created automatically when you use aes() to map a data column to an aesthetic. You don't have a data column that you're mapping to the linetype aesthetic, so we need to create one.

Series1$series = 1
Series2$series = 2
all_series = rbind(Series1, Series2)

Now we've all the data together and plotting is easy:

ggplot(all_series,
       aes(x = Date, y = Total, color = County, linetype = factor(series))) + 
    geom_line()

Automatic legend, only one geom_line call, using ggplot as it's meant to be used: with tidy data.

1
votes

You are really close...

ggplot() + 
      geom_line(data = Series1, aes(x = Date, y = Total, color = County), linetype="solid") +
      geom_line(data = Series2, aes(x = Date, y = Total, color = County), linetype="dashed")+ scale_linetype_manual()

enter image description here