R中不同组的时间序列多重图 [英] Time series multiple plot for different group in R
本文介绍了R中不同组的时间序列多重图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含多个变量(大约50个)的大型数据框,第一列为 date
,第二列为 id
.
I have a large data frame of several variables (around 50) with first column as date
and second column id
.
我的数据大致如下:
df <- data.frame(date = c("01-04-2001 00:00","01-04-2001 00:00","01-04-2001 00:00",
"01-05-2001 00:00","01-05-2001 00:00","01-05-2001 00:00",
"01-06-2001 00:00","01-06-2001 00:00","01-06-2001 00:00",
"01-07-2001 00:00","01-07-2001 00:00","01-07-2001 00:00"),
id = c(1,2,3,1,2,3,1,2,3,1,2,3), a = c(1,2,3,4,5,6,7,8,9,10,11,12),
b = c(2,2.5,3,3.2,4,4.6,5,5.6,8,8.9,10,10.6))
我希望在同一变量图中分别对所有三个id进行时间序列图绘制,在不同图中分别使用 a
和 b
.
I want time series plots for all three ids separately in same graph of variables, a
and b
in different graphs.
我尝试了 ggplot
,但没有成功.请帮助我
I tried ggplot
but it didn't work. Please help me
推荐答案
阅读评论后,也许您应该尝试执行以下操作:
After reading the comments, maybe you should try something like this:
library(tidyr)
df2 <- gather(df, variable, value, -date, -id)
vars <- unique(df2$variable)
library(ggplot2)
for (i in 1:length(vars)) {
ggplot() +
geom_line(data = subset(df2, variable == vars[[i]]),
aes(date, value, group = id, color = factor(id))) +
ylab(as.character(vars[[i]])) +
ggsave(file = paste0(vars[[i]], ".png"))
}
这应为数据框中的每个变量保存一个PNG(并根据您的请求将每个图的y标签更改为变量名 )
This should save a PNG for each variable in your dataframe (and will change y label of every plot to variable name, as per your request)
这篇关于R中不同组的时间序列多重图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文