Plotting daytime (without date) in ggplot2
Asked Answered
P

1

7

I want to scatterplot a numeric vector versus daytime (%H:%M) in ggplot2.

I understand that

as.POSIXct(dat$daytime, format = "%H:%M")

is the way to go in terms of formatting my timedata, but the output vector will still include a date (today's date). Consequently, the axis ticks will include the date (March 22nd).

ggplot(dat, aes(x=as.POSIXct(dat$daytime, format = "%H:%M"), y=y, color=sex)) +
geom_point(shape=15,
position=position_jitter(width=0.5,height=0.5))

image of the plot output

Is there a way to get rid of the date alltogether, especially in the plot axis? (All info I have found on messageboards seem to refer to older versions of ggplot with now defunct date_format arguments)

Polyethylene answered 22/3, 2017 at 11:53 Comment(4)
DId you try using scale_x_continuous(labels = NULL) ?Halfhearted
date_format() is now in the scales packageAddi
I think scale_x_continuous does not work on POSIXct vectors, as it produces an error message: Error in as.POSIXct.numeric(value) : 'origin' muss angegeben werdenPolyethylene
Is date_format() even useful here? Looks like date_format(format = "%Y-%m-%d", tz = "UTC") also needs a date, so I will probably need another ggplot2 solution. There is this: link but it either doesn't address my case, or I don't understand it.Polyethylene
F
7

You can provide a function to the labels parameter of scale_x_datetime() or use the date_label parameter:

# create dummy data as OP hasn't provided a reproducible example
dat <- data.frame(daytime = as.POSIXct(sprintf("%02i:%02i", 1:23, 2 * (1:23)), format = "%H:%M"),
                 y = 1:23)
# plot
library(ggplot2)
ggplot(dat, aes(daytime, y)) + geom_point() + 
  scale_x_datetime(labels = function(x) format(x, format = "%H:%M"))

EDIT: Or, even more concise you can use the date_label parameter (thanks to aosmith for the suggestion).

ggplot(dat, aes(daytime, y)) + geom_point() + 
  scale_x_datetime(date_label = "%H:%M")

enter image description here

Freehand answered 22/3, 2017 at 15:19 Comment(2)
Or use the date_labels argument as a shortcut, date_labels = "%H:%M".Lal
Thank you very much! Now I wonder if this thread will turn out to be one of those stackoverflow-"top 1 google search results" that I often find when searching for a specific coding issue.. # create dummy data as OP hasn't provided a reproducible example Okay I get it, will include code for dummy data next time :)Polyethylene

© 2022 - 2024 — McMap. All rights reserved.