Question

I'd like to create a custom x-axis label like it was done here: http://blog.earlh.com/index.php/2009/07/plotting-with-custom-x-axis-labels-in-r-part-5-in-a-series/

But when I'm trying to set the x axis label with:

at <- format(SubDateTime$DateTime, "%H") %in% c("00", "06", "12", "18")
axis(side = 1,at = SubDateTime$DateTime[at],
      labels = format(SubDateTime$DateTime[at], "%a-%H"))

I receive the following error:

Error in axis(side = 1, at = SubDateTime$DateTime[at], 
              labels = format(SubDateTime$DateTime[at],  
           : (list) object cannot be coerced to type 'double'

SubDateTime$DateTime is a POSIXlt class with two dates (2013-06-01 and 2013-06-02) and the hourly time. I want to add "Sun-00", "Sun-06", "Sun-12", etc to the x axis.

Confusing to me is when I do the example from the link above it works fine.

Thx

Edit:

 plot(x = SubDateTime$DateTime,
 y = SubConsumption$Load.MW,
 type = "l",
 lwd = 2,
 ylim = c(0, max(SubConsumption$Load.MW, na.rm = FALSE)*1.2),
 main = "Spot Price June 01 to June 02",
 xlab = "",
 ylab = "",
 bty = "l",
 xaxt = "n")

What information about SubDateTime$DateTime do you need?

Was it helpful?

Solution

That looks correct (If it is applied to a POSIXct vector). As I said in the comment, POSIXlt formatted columns are actually lists and will give you strange error reports if you attempt operations on them. Try this:

dtime <- as.POSICct(SubDateTime$DateTime)
at <- format(SubDateTime$DateTime, "%H") %in% c("00", "06", "12", "18")
axis(side = 1,at = SubDateTime$DateTime[at],
      labels = format(SubDateTime$DateTime[at], "%a-%H"))

Contrast with:

dtime <- seq(as.POSIXct("2013-06-01 00:00:00") ,  
             as.POSIXct("2013-06-02 00:00:00"), by="5 min")

dtime.lt <- as.POSIXlt(dtime)
at <- format(dtime.lt, "%H") %in% c("00", "06", "12", "18")
axis(side = 1,at = dtime.lt[at],
       labels = format(dtime.lt[at], "%a-%H"))
Error in axis(side = 1, at = dtime.lt[at], labels = format(dtime.lt[at],  : 
  (list) object cannot be coerced to type 'double'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top