Change the x number of ticks on a time series using ggplot2

I am trying to plot a time series x_output

that looks like this:

              timestamp   city wait_time weekday     time
    2015-07-14 09:00:00 Boston       1.6 Tuesday 09:00:00
    2015-07-14 09:01:00 Boston       1.8 Tuesday 09:00:00
    2015-07-14 09:02:00 Boston       2.4 Tuesday 09:00:00
    2015-07-14 09:03:00 Boston       2.9 Tuesday 09:00:00
    2015-07-14 09:04:00 Boston       4.5 Tuesday 09:00:00
    2015-07-14 09:05:00 Boston       5.6 Tuesday 09:00:00

      

This is how I draw it:

brks <- seq(1, length(x_output$timestamp), 10)
brks_labels <- x_output[brks, ]

p <- ggplot(x_output, aes(x=as.character(timestamp), y=wait_time, group=city)) + geom_line(aes(color=city), size=1.5) + theme(axis.text.x = element_text(angle = 90, hjust=1), legend.position = "bottom") + labs(x=NULL, y="Waiting time (minutes)") + scale_x_discrete(breaks = brks, labels = brks_labels)
print(p)

      

I have to use x_output$timestamp

as a symbol (i.e. a categorical variable), because otherwise ggplot2 considers it continuous and includes white blank areas that have no meaning.

For some reason, however, scale_x_discrete

doesn't work. I believe I have an input for breaks, but now these shortcuts are not showing. Does anyone know why? Here are the graphs:

enter image description here

I'm trying to just show the labels every 10 timestamps on the x-axis (which is why I was putting the breaks in the array like brks

).

+3


source to share


1 answer


Your breaks should be of the same type as yours aes(x=

, i.e. scale_x_discrete(breaks=x_output$timestamp[brks])

...

However, remember that converting your timestamp to categorical like this may not be accurate in the timescale, then - if a missed timestamp is skipped by 2 minutes and the rest skipped by 1, it will not be reflected in your graph.



I think you are better off storing X as a date and time using + scale_x_datetime(breaks=date_breaks("10 mins"))

. If you have multiple space-separated time windows with no data, you can use a variable to specify which "window" each line belongs to, and facet_wrap

to build windows side-by-side, allowing you to skip spaces while maintaining the x-axis scale ... For example. you might be facet_wrap

on weekday

if your data was only meant for a specific window every day.

+1


source







All Articles