简体   繁体   English

使用 ggplot 将图例添加到多个时间序列图

[英]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因为它意味着要使用:使用整洁的数据。

You are really close...你真的很亲近...

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")+ scale_linetype_manual()

在此处输入图片说明

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

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