[英]Time series multiple plot for different group in R
我有一個包含多個變量(大約50個)的大型數據框,其中第一列為date
,第二列為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
在不同的圖中。
我試過ggplot
但它沒有用。 請幫我
你的意思是這樣的嗎?
library(reshape)
library(lattice)
df2 <- melt(df, id.vars = c("date", "id"), measure.vars = c("a", "b"))
xyplot(value ~ date | variable, group = id, df2, t='l')
附錄
# The following is from a comment by jbaums.
# It will create a single plot/file for each variable of df2
png('plots%02d.png')
xyplot(value ~ date | variable, group = id, df2, t='l', layout=c(1, 1),
scales=list(alternating=FALSE, tck=1:0))
dev.off()
您還可以將scales
relation='free'
添加到scales
以便為每個圖單獨計算y軸限制。
以下是如何在ggplot中執行此操作,使用tidyr包以正確的格式獲取它:
library(ggplot2)
library(tidyr)
library(dplyr)
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))
然后使用dplyr的group_by和do函數,我們可以保存多個圖。
df %>%
gather(variable, value, -date, -id) %>%
mutate(id = factor(id)) %>%
group_by(variable) %>%
do(
qplot(data = ., x = date, y = value, geom = "line", group = id, color = id, main = paste("variable =", .$variable)) +
ggsave(filename = paste0(.$variable, ".png")
)
)
編輯:閱讀評論后,也許你應該嘗試這樣的事情:
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標簽更改為變量名 )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.