使用 ggplot2 绘制 xts 对象

问题描述 投票:0回答: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

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

r ggplot2 xts
4个回答
12
投票

zoo 中的

autoplot.zoo
方法(zoo 由 xts 自动拉入)也将使用 ggplot2 为 xts 对象创建绘图。如果您需要额外的几何图形,它支持 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
了解更多信息。


10
投票

将小写“index”更改为大写“Index”

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

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)


0
投票

如果有帮助,我发现显式传递数据会起作用:

my_xts %>%
  ggplot(mapping = aes(x = Index, y = .)) +
  geom_line()

我希望这对你有用!

© www.soinside.com 2019 - 2024. All rights reserved.