[英]Add legend to multiple time-series plot using ggplot
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:情节是这样的:
Now I just need to add one legend showing that solid line represents Series1 and dashed line represents Series2.现在我只需要添加一个图例,显示实线代表系列 1,虚线代表系列 2。 How can I do this?
我怎样才能做到这一点?
Legends are created automatically when you use aes()
to map a data column to an aesthetic.当您使用
aes()
将数据列映射到美学时,会自动创建图例。 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.自动图例,只有一个
geom_line
调用,使用ggplot
因为它意味着要使用:使用整洁的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.