使用ggplot2绘制XTS对象 [英] Plotting an xts object using ggplot2
问题描述
我想使用ggplot2绘制xts对象,但出现错误.这是我在做什么:
I'm wanting to plot an xts object using ggplot2 but getting an error. Here is what I'm doing:
dates <- c("2014-10-01", "2014-11-01", "2014-12-01", "2015-01-01", "2015-02-01")
value <- as.numeric(c(3, 4, 5, 6, 5))
new_df <- data_frame(dates, value)
new_df$dates <- as.Date(dates)
new_df <- as.xts(new_df[,-1], order.by = new_df$dates)
现在,我尝试使用ggplot2对其进行绘制:
Now I try to plot it using ggplot2:
ggplot(new_df, aes(x = index, y = value)) + geom_point()
我收到以下错误:
错误(函数(...,row.names = NULL,check.rows = FALSE, check.names = TRUE ,:参数暗示不同的行数:0, 5
Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, : arguments imply differing number of rows: 0, 5
我不确定自己做错了什么.
I'm not quite sure what it is that I'm doing wrong.
推荐答案
Zoo中的autoplot.zoo
方法(zoo由xts自动引入)也将使用ggplot2为xts对象创建图.如果需要其他几何图形,它支持ggplot2的+....参见?autoplot.zoo
The autoplot.zoo
method in zoo (zoo is automatically pulled in by xts) will create plots using ggplot2 for xts objects too. It supports ggplot2's +... if you need additional geoms. See ?autoplot.zoo
library(xts)
library(ggplot2)
x_xts <- xts(1:4, as.Date("2000-01-01") + 1:4) # test data
autoplot(x_xts, geom = "point")
zoo还具有fortify.zoo
,它将把Zoo或xts对象转换为data.frame:
zoo also has fortify.zoo
which will convert a zoo or xts object to a data.frame:
fortify(x_xts)
给予:
Index x_xts
1 2000-01-02 1
2 2000-01-03 2
3 2000-01-04 3
4 2000-01-05 4
fortify
泛型在ggplot2中,因此如果您没有加载ggplot2,则直接使用fortify.zoo(x_xts)
.
The fortify
generic is in ggplot2 so if you do not have ggplot2 loaded then use fortify.zoo(x_xts)
directly.
有关更多信息,请参见?fortify.zoo
.
See ?fortify.zoo
for more information.
这篇关于使用ggplot2绘制XTS对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!