我对R很陌生,我正在尝试使用ggplot2在一张图中同时绘制三个时间序列线(使用不同的颜色)。我想为三行添加图例,但无法为图形生成图例。非常感谢您的建议。
码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")
数据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
[例如,您应该首先尝试使用pivot_longer
中的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")
以您的示例为例,它给出了这样的内容:
它回答了您的问题吗?
可复制的示例
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))