Kaja Kaja - 1 month ago 12
R Question

scaling x-axis in ggplot

I have an Object classt of

xts
. I would like to plot this object with
ggplot2


my
xts
object:

structure(c(463829L, 469849L, 608148L, 470825L, 560057L, 431183L,
418000L, 508168L, 422579L, 589829L, 462264L, 487183L, 612174L,
467904L, 454620L, 450243L, 549898L, 422026L, 508311L, 385633L,
420200L, 619074L, 462605L, 465353L, 565804L, 464841L, 505977L,
624608L, 491175L, 459701L, 563406L, 461595L, 499607L, 674799L,
505167L, 637375L, 500131L, 473494L, 488527L, 613972L, 468938L,
454034L, 566511L, 456879L, 592797L, 491368L, 481690L, 597927L
), .Tsp = c(2012, 2015.91666666667, 12), class = "ts")


I woulf like to have also month numbers on my plot. I have tried this code:

library(ggplot2)
library(zoo)
library(scales)
autoplot(as.zoo(a2)) + geom_line()
+scale_x_date(format = "%b-%Y")


but I get this error:

Error in continuous_scale(aesthetics, "date", identity, breaks = breaks, :
unused argument (format = "%b-%Y")


What should I do to do this job? Like this plot but with month:
enter image description here

Answer

I think the problem is that the index to your time series is in decimal date (i.e., numeric) format, and scale_x_date is expecting something in date format.

Here's some code that gets close to what I think you want. It involves creating a zoo object with the index in date format first, then plotting that. Like:

a3 <- zoo(a2, order.by = as.Date(yearmon(index(a2))))
p <- autoplot(a3)
p + scale_x_date(date_breaks = "1 month")
  + theme(axis.text.x = element_text(angle = 90))

I think you'll want to tinker with the options in scale_x_date to improve the look of the result, but this should get you on the right path, I think.

Comments