muffel
muffel

Reputation: 7380

format y axis for plotting time of day with qplot/ggplot2

I have many data entries with two properties, the time of day (24h format, UTC, no date given) and a string containing the type of data.

I want to visualize the distribution of entries along the time axis for each type.

Consider the following example code:

library(ggplot2)

time <- c("22:12", "11:04", "00:04", "23:45", "12:04", "16:33")
type <- c("Foo", "Bar", "Foo", "Foo", "Foo", "Bar")

data <- data.frame(time, type)

qplot(data$type, strptime(data$time, "%H:%M")) +
  scale_y_datetime(date_breaks="1 hour", date_labels="%H:%M") + xlab("Type") + ylab("Time")

I want the chart to display the type on the x axis and the y axis to be in the range from 00:00 to 23:59 (no matter what actual times are in the dataset).

Not only does the time ranges from 21.00 to 22.00 (overflowing once), but the single entries are also displayed wrong (just look at the two 'Bar' entries):

enter image description here

Do you have any idea why the axis labels are that strange, and why the time it not plotted at the correct position? Maybe a timezone issue?

Upvotes: 4

Views: 1252

Answers (1)

Richard Telford
Richard Telford

Reputation: 9923

Since scales:::date_format takes UTC by default and I cannot see how to change this argument through scale_y_datetime, the simplest solution is probably to specify that you are using UTC whatever your real timezone.

qplot(data$type, strptime(data$time, "%H:%M", tz = "UTC")) +
  scale_y_datetime(date_breaks="1 hour", date_labels="%H:%M", expand = c(0,0)) +
  xlab("Type") + ylab("Time")

Upvotes: 4

Related Questions