Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting an xts object using ggplot2

Tags:

r

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)

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.

like image 285
Greg Martin Avatar asked Dec 02 '22 13:12

Greg Martin


2 Answers

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

ggplot(new_df, aes(x = Index, y = value)) + geom_point()
like image 195
user2510479 Avatar answered Dec 17 '22 23:12

user2510479


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.

like image 35
G. Grothendieck Avatar answered Dec 18 '22 01:12

G. Grothendieck