我正在嘗試通過對year列進行分組來創建一些資料的時間序列圖。在下面的代碼中,當我嘗試按gather取值時year,該函式改為選擇另一列的標題 ( tmean) 作為key,而我希望列下year的值為key。
我怎樣才能解決這個問題?
樣本資料
Date = c("2010-01", "2010-02", "2010-03","2010-04" "2011-01", "2011-02", "2011-03", "2011-04")
year = c(2010, 2010, 2010, 2010, 2011, 2011, 2011, 2011)
month = c(01, 02, 03, 04, 01, 02, 03, 04)
tmean = c(15, 20, 30, 25 18, 23, 33, 28)
代碼
library(tidyverse)
df = data.frame(tmean. Date, year, month)
df = df %>%
select(Date, tmean, year) %>%
gather(key = "variable", value = "value", -Date)
ggplot(df, aes(x = Date, y = value))
geom_line(aes(color = variable, linetype = variable)
想要的情節

uj5u.com熱心網友回復:
如果你想生成你想要的圖,你真的不需要重塑你的資料框。
library(ggplot2)
Date = c("2010-01", "2010-02", "2010-03","2010-04", "2011-01", "2011-02", "2011-03", "2011-04")
year = c(2010, 2010, 2010, 2010, 2011, 2011, 2011, 2011)
month = c(01, 02, 03, 04, 01, 02, 03, 04)
tmean = c(15, 20, 30, 25, 18, 23, 33, 28)
df = data.frame(tmean, Date, year, month)
ggplot(df, aes(month, tmean, color = as.character(year)))
geom_line()
labs(color = "Year")

由reprex 包創建于 2022-04-02 (v2.0.1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/454404.html
下一篇:在R中折疊虛擬列
