3

全部。

我在 stackoverflow 上阅读了几条之前的消息,并浏览了 zoo 和 ggplot2 的文档,但没有找到任何合适的答案。

假设我有一个名为“数据”的动物园对象。平面文件中的原始数据如下:

Date,Quote1,Quote2,Quote3,Quote4,Quote5
18/07/2008,42.36,44.53,28.4302,44.3,42
21/07/2008,43.14,44.87,28.6186,44.83,43.27
22/07/2008,43.26,44.85,28.6056,44.86,42.84
23/07/2008,44.74,45.61,29.7558,45.69,#N/A
24/07/2008,43.99,45.14,29.2944,45.19,#N/A
25/07/2008,43.18,45.33,29.4569,45.46,43.65
28/07/2008,43.45,44.72,28.5016,44.89,43.31
29/07/2008,43.49,44.8,28.1247,44.88,42.85
30/07/2008,44.55,45.54,28.0727,45.58,43.67
31/07/2008,43.36,45.5,27.9818,45.63,43.91
01/08/2008,43.34,44.75,28.0792,44.69,43.04

现在,我想在一个折线图上绘制这五种金融产品的时间序列,以便比较它们的演变。

我希望使用ggplot2

有人愿意给我一些提示吗?

4

3 回答 3

9

如果data是你的动物园对象,那么试试这个(并查看?autoplot.zoo更多信息):

p <- autoplot(data, facet = NULL)
p

或者这可能是因为我认为linetype在同一个面板中使用这么多系列的自动变化看起来不太好:

p + aes(linetype = NULL)

在此处输入图像描述

于 2012-12-12T22:21:29.327 回答
4

这是一种方法:

df <- read.csv(text = "Date,Quote1,Quote2,Quote3,Quote4,Quote5
18/07/2008,42.36,44.53,28.4302,44.3,42
21/07/2008,43.14,44.87,28.6186,44.83,43.27
22/07/2008,43.26,44.85,28.6056,44.86,42.84
23/07/2008,44.74,45.61,29.7558,45.69,#N/A
24/07/2008,43.99,45.14,29.2944,45.19,#N/A
25/07/2008,43.18,45.33,29.4569,45.46,43.65
28/07/2008,43.45,44.72,28.5016,44.89,43.31
29/07/2008,43.49,44.8,28.1247,44.88,42.85
30/07/2008,44.55,45.54,28.0727,45.58,43.67
31/07/2008,43.36,45.5,27.9818,45.63,43.91
01/08/2008,43.34,44.75,28.0792,44.69,43.04", na.string = "#N/A")

df$Date <- strptime(df$Date, format = "%d/%m/%Y")

创建一个zoo对象:

library(zoo)
dat <- zoo(df[-1], df$Date)

将对象转换为数据框ggplot2

df_new <- data.frame(value = as.vector(dat),
                     time = time(dat),
                     quote = rep(names(dat), each = nrow(dat)))

阴谋:

library(ggplot2)
ggplot(df_new, aes(y = value, x = time, colour = quote)) + geom_line()

在此处输入图像描述

于 2012-12-12T21:01:53.797 回答
1

这是另一种略有不同的方法,使用 reshape 中的 melt

# Read your data and format date (as proposed by Sven)

df <- read.csv(text = "Date,Quote1,Quote2,Quote3,Quote4,Quote5
18/07/2008,42.36,44.53,28.4302,44.3,42
21/07/2008,43.14,44.87,28.6186,44.83,43.27
22/07/2008,43.26,44.85,28.6056,44.86,42.84
23/07/2008,44.74,45.61,29.7558,45.69,#N/A
24/07/2008,43.99,45.14,29.2944,45.19,#N/A
25/07/2008,43.18,45.33,29.4569,45.46,43.65
28/07/2008,43.45,44.72,28.5016,44.89,43.31
29/07/2008,43.49,44.8,28.1247,44.88,42.85
30/07/2008,44.55,45.54,28.0727,45.58,43.67
31/07/2008,43.36,45.5,27.9818,45.63,43.91
01/08/2008,43.34,44.75,28.0792,44.69,43.04", na.string = "#N/A")

df$Date <- strptime(df$Date, format = "%d/%m/%Y")

library(reshape)
# reshape your data with melt
melted <- melt(df[-1])
# add dates
melted2 <- cbind(df$Date,melted)
# plot with ggplot
ggplot(melted2,aes(y = value, x = melted2[,1], color = variable)) + geom_line()

阴谋

于 2012-12-12T21:45:58.663 回答