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)

Sathish
  • 12,453
  • 3
  • 41
  • 59
  • DId you try using `scale_x_continuous(labels = NULL)` ? – Adi Sarid Mar 22 '17 at 11:58
  • 1
    `date_format()` is now in the `scales` package – GGamba Mar 22 '17 at 12:10
  • 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 werden` – Robin Gleeson Mar 22 '17 at 14:00
  • 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](http://docs.ggplot2.org/current/scale_date.html) but it either doesn't address my case, or I don't understand it. – Robin Gleeson Mar 22 '17 at 14:04

1 Answers1

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

Community
  • 1
  • 1
Uwe
  • 41,420
  • 11
  • 90
  • 134
  • 3
    Or use the `date_labels` argument as a shortcut, `date_labels = "%H:%M"`. – aosmith Mar 22 '17 at 19:49
  • 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 :) – Robin Gleeson Mar 28 '17 at 09:26