Plotting an xts object using ggplot2

爷,独闯天下 提交于 2020-01-23 08:33:51

问题


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)

Now I try to plot it using 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

I'm not quite sure what it is that I'm doing wrong.


回答1:


change lower case 'index' to upper case 'Index'

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



回答2:


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 also has fortify.zoo which will convert a zoo or xts object to a 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.

See ?fortify.zoo for more information.




回答3:


Do you need to use an xts object?

You can plot date/times without the use of 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)



来源:https://stackoverflow.com/questions/43345388/plotting-an-xts-object-using-ggplot2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!