geom_line 在 R 中按年份分组
geom_line group by year in R
我正在尝试通过对 year
列进行分组来创建一些数据的时间序列图。在下面的代码中,当我尝试通过 year
来 gather
值时,该函数会选择另一列的 header (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)
想要的情节
如果你想生成你想要的图,你真的不需要重塑你的数据框。
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 package (v2.0.1)
创建于 2022-04-02
我正在尝试通过对 year
列进行分组来创建一些数据的时间序列图。在下面的代码中,当我尝试通过 year
来 gather
值时,该函数会选择另一列的 header (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)
想要的情节
如果你想生成你想要的图,你真的不需要重塑你的数据框。
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 package (v2.0.1)
创建于 2022-04-02