簡體   English   中英

使用 ggplot 將圖例添加到多個時間序列圖

[英]Add legend to multiple time-series plot using ggplot

我有兩個時間序列數據要顯示在同一個圖表上。 這兩個系列都有三列:日期、縣和值。 這是我的代碼:

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

情節是這樣的:

陰謀

現在我只需要添加一個圖例,顯示實線代表系列 1,虛線代表系列 2。 我怎樣才能做到這一點?

當您使用aes()將數據列映射到美學時,會自動創建圖例。 您沒有要映射到線型美學的數據列,因此我們需要創建一個。

Series1$series = 1
Series2$series = 2
all_series = rbind(Series1, Series2)

現在我們把所有的數據放在一起,繪圖很容易:

ggplot(all_series,
       aes(x = Date, y = Total, color = County, linetype = factor(series))) + 
    geom_line()

自動圖例,只有一個geom_line調用,使用ggplot因為它意味着要使用:使用整潔的數據。

你真的很親近...

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