0

I am quite new to R and am attempting to plot three time series lines simultaneously in one graph (using different colors) making use of ggplot2. And I would like to add legend for the three lines but cannot produce the legend for the graph. Your suggestions are highly appreciated.

Code
ggplot ggplot(vn, aes(x=date)) + `ggplot enter code here`
      geom_line(aes(y = newcase),size=1, color="red") + 
      geom_line(aes(y = recovered),color="blue", size=1)+ 
      geom_line(aes(y = confirmed), color="green", linetype="solid", size=1)+
      xlab("Date")+
      ylab("People")+
      scale_x_date(date_breaks = "1 week", date_labels = "%d/%m")

Data
Date        confirmed  recovered   newcase
2020-03-15  56  16  0
2020-03-16  61  16  4
2020-03-17  66  16  3
2020-03-18  75  16  7
2
  • 1
    The problem is you've plotted three separate geom_line(), each with a manually defined color. To use legends, you need to convert the data to long format (tidyr::pivot_longer() can do this!) so you have one variable to plot, and plot them with one geom_line(aes(color = variablename)). Questions here and here are similar to yours and could help.
    – Jan Boyer
    Commented Apr 20, 2020 at 23:24
  • you suggestion are really helpful so my problem solved. Thank you so much
    – Quang
    Commented Apr 21, 2020 at 7:00

1 Answer 1

0

You should try to reshape your dataframe first using for example pivot_longer function from tidyr:

library(dplyr)
library(tidyr)
library(ggplot2)
library(lubridate)

data %>% pivot_longer(cols = confirmed:newcase, names_to = "Cases", values_to = "values") %>%
  ggplot(aes(x = ymd(Date), y = values, color = Cases))+
  geom_line()++
  xlab("Date")+
  ylab("People")+
  scale_x_date(date_breaks = "1 week", date_labels = "%d/%m")

With your example, it gives something like that:

enter image description here

Does it answer your question ?


reproducible example

data <- data.frame(Date = c("2020-03-15","2020-03-16","2020-03-17","2020-03-18"),
                   confirmed = c(56,61,66,75),
                   recovered = c(16,16,16,16),
                   newcase = c(0,4,3,7))
1
  • Exactly what I need, and thanks your help I can solve the problem now. Thank you so much for your kindly help
    – Quang
    Commented Apr 21, 2020 at 7:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.