Skip to content
Prev 393604 / 398503 Next

Customise Plot tick label on time series plot using date series

?s 05:11 de 13/01/2023, roslinazairimah zakaria escreveu:
Hello,

There are two main problems with your code:

1. The time column is not a date, it's a character column. Start by 
coercing it to a real date class.

2. autoplot is a ggplot2 function and it does not support objects of 
class "ts", you should first coerce the data set dt to class "zoo" or to 
class "xts". In the code below I will coerce to class "zoo".


# When calling non-base functions
# always start the scripts by loading
# the packages where those functions
# can be found
library(ggplot2)
library(zoo)

# coerce the time column to class "Date"
dt$time <- as.Date(dt$time, "%d/%m/%Y")
str(dt)
# 'data.frame':	349 obs. of  2 variables:
#  $ time             : Date, format: "2014-01-01" ...
#  $ cnt_charge_events: int  2 3 4 3 5 6 3 5 4 4 ...


# now coerce the time series to a "zoo" time series
dt_ts <- zoo(dt$cnt_charge_events, order.by = dt$time)

# the x axis labels are right, quarterly date breaks are automatic
# and plot the object dt_ts, not its second column dt_ts[,2]
autoplot(dt_ts) +
   xlab("Daily") +
   ylab("Charge counts")


# scale_x_date allows for custom breaks and labels,
# here monthly breaks and the same labels format
# with more axis labels they need to be rotated in order to be readable
# (as a side note I have displayed the axis labels in one instruction only)
autoplot(dt_ts) +
   labs(x = "Daily", y = "Charge counts") +
   scale_x_date(date_breaks = "1 month", date_labels = "%b %Y") +
   theme(axis.text.x = element_text(angle = 60, vjust = 1, hjust = 1))



Hope this helps,

Rui Barradas