简体   繁体   中英

Legend in multiple line graph in ggplot2

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

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:

在此处输入图像描述

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM