【发布时间】:2018-02-23 19:10:39
【问题描述】:
我想绘制一个动物园对象的多列图。例如,
df <- zoo(data.frame(A = c(2.3, 4.4, 5.2),
B = c(5.5, 1.7, 4.4),
C = c(2.5, 7.7, 3.3)),
order.by = c(as.Date("2010-10-1"),
as.Date("2010-10-5"),
as.Date("2010-10-7")))
给出:
A B C
2010-10-01 2.3 5.5 2.5
2010-10-05 4.4 1.7 7.7
2010-10-07 5.2 4.4 3.3
转换zoo对象并创建ggplot所需的长数据形式的一种丑陋方法是:
var.vec <- NULL
val.vec <- NULL
num.rows <- nrow(df)
for(i in 1:ncol(df))
{
v <- rep(colnames(df)[i], num.rows)
var.vec <- c(var.vec, v)
val.vec <- c(val.vec, df[, i])
}
df1 <- data.frame(x = time(new.ticker.prices),
val = val.vec,
variable = var.vec,
stringsAsFactors = FALSE)
和ggplot情节声明:
ggplot(data = df1, aes(x=x, y=val)) + geom_line(aes(colour=variable))
这行得通。
为了尝试使用更优雅的解决方案,我尝试将 df 转换为数据框对象并使用“reshape2”包中的“melt”,但我无法让它工作。
有没有更优雅的方式使用 ggplot 绘制 zoo 对象 df 的列?
【问题讨论】: