[英]Plotting an xts object using ggplot2
I'm wanting to plot an xts object using ggplot2 but getting an error. 我想用ggplot2绘制一个xts对象,但是收到错误。 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)
Now I try to plot it using ggplot2: 现在我尝试使用ggplot2绘制它:
ggplot(new_df, aes(x = index, y = value)) + geom_point()
I get the following error: 我收到以下错误:
Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, : arguments imply differing number of rows: 0, 5
错误(函数(...,row.names = NULL,check.rows = FALSE,check.names = TRUE,:参数意味着不同的行数:0,5
I'm not quite sure what it is that I'm doing wrong. 我不太确定我做错了什么。
将小写'指数'改为大写'指数'
ggplot(new_df, aes(x = Index, y = value)) + geom_point()
The autoplot.zoo
method in zoo (zoo is automatically pulled in by xts) will create plots using ggplot2 for xts objects too. 动物园中的
autoplot.zoo
方法(动物园由xts自动拉入)也将使用ggplot2为xts对象创建绘图。 It supports ggplot2's +... if you need additional geoms. 它支持ggplot2的+ ...如果你需要额外的geoms。 See
?autoplot.zoo
见
?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 also has fortify.zoo
which will convert a zoo or xts object to a data.frame: zoo还有
fortify.zoo
,它将动物园或xts对象转换为data.frame:
fortify(x_xts)
giving: 赠送:
Index x_xts
1 2000-01-02 1
2 2000-01-03 2
3 2000-01-04 3
4 2000-01-05 4
The fortify
generic is in ggplot2 so if you do not have ggplot2 loaded then use fortify.zoo(x_xts)
directly. fortify
泛型在ggplot2中,所以如果你没有加载ggplot2,那么直接使用fortify.zoo(x_xts)
。
See ?fortify.zoo
for more information. 有关更多信息,请参阅
?fortify.zoo
。
Do you need to use an xts
object? 你需要使用
xts
对象吗?
You can plot date/times without the use of xts
. 您可以在不使用
xts
情况下绘制日期/时间。 Here is an example using what you provided above. 以下是使用您在上面提供的内容的示例。 You could format it how you want beyond that.
除此之外,您可以将其格式化。
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)
require(scales)
ggplot(new_df, aes(x = dates, y = value)) + geom_point() +
scale_x_date(labels = date_format("%Y-%m-%d"), breaks = date_breaks("1 month")) +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
ggsave("time_plot.png", height = 4, width = 4)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.