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))
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)
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With