简体   繁体   English

ggplot2 中多折线图中的图例

[英]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.我对 R 很陌生,我正在尝试在一张图中同时使用 plot 三个时间序列线(使用不同的颜色),使用 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 :您应该尝试首先使用例如pivot_longer function 从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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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