Espejito
Espejito

Reputation: 480

R: Plotting hour data

I'm just another R rookie who is struggling with datetime objects in R. Can you tell me what is wrong in my code when it gives me a picture like this? I want the x-axis to be hours only, without the date. And sure the hour column of the data frame shouldn't look like this → 2021-07-09 07:30:00. It should be 07:30, 16:30, 18:10 and so on. The date of observations is in another column. Below is the code I used, and it worked just fine with another data frame, so I'm puzzled.

df$hour <- as.POSIXct(df$hour, format="%H:%M") and ggplot(data=df, aes(x=df$hour)) + geom_freqpoly()

enter image description here

Upvotes: 1

Views: 1036

Answers (1)

heds1
heds1

Reputation: 3428

Like stefan said, it's hard to know exactly what will work with your data. But I think you probably want to look at scale_x_datetime. For example:

library(dplyr)
library(ggplot2)

dat <- tibble(
    hour = as.POSIXct(c(
        "2020-01-01 12:00",
        "2020-01-01 13:00",
        "2020-01-01 14:00"
    )),
    y = 1:3
)

dat %>%
    ggplot(aes(x = hour, y = y)) +
        geom_line(group = 1) +
        scale_x_datetime(
            date_breaks = "1 hour",
            date_labels = "%H:%M"
        )

plot

For a bit more context, when you write df$hour <- as.POSIXct(df$hour, format="%H:%M"), you aren't actually formatting that variable, and it stays as a date-time object. (Print df$hour to see what I mean.) Something like this might work better, using the format function (with, confusingly, the format argument):

format(as.POSIXct(df$hour), format = "%H:%M")

But in any case, I would be inclined to preserve all the information in that variable, and just do the formatting in ggplot itself with scale_x_datetime.

This post has some more context.

Upvotes: 1

Related Questions