Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting daytime (without date) in ggplot2

Tags:

r

ggplot2

posixct

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)

like image 904
Robin Gleeson Avatar asked Mar 22 '17 11:03

Robin Gleeson


1 Answers

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

like image 56
Uwe Avatar answered Nov 03 '22 20:11

Uwe