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.
change lower case 'index' to upper case 'Index'
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. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With