使用ggplot2绘制xts对象

4

我想使用ggplot2绘制一个xts对象,但是出现了错误。这是我的做法:

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绘制它:

ggplot(new_df, aes(x = index, y = value)) + geom_point()

我遇到了以下错误:

在 (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, : 参数指定的行数不同: 0, 5

我不太确定我做错了什么。

4个回答

12

在zoo中,autoplot.zoo方法(xts会自动引入zoo库)可以为xts对象创建使用ggplot2的图形。如果需要其他的geoms,它还支持ggplot2的+...语法。请参阅?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:

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)

有关更多信息,请参见 ?fortify.zoo


请参考ggplot2中的autoplot - Samuel

10

将小写的 'index' 改为大写的 'Index'

ggplot(new_df, aes(x = Index, y = value)) + geom_point()

0
如果有帮助的话,我发现明确传递数据会起作用。
my_xts %>%
  ggplot(mapping = aes(x = Index, y = .)) +
  geom_line()

希望这对你有帮助!

0
你需要使用一个 xts 对象吗?
你可以不使用 xts 来绘制日期/时间。以下是使用你提供的内容的示例。你可以在此基础上进行格式化。
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)

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接