在 ggplot2 中绘制白天(无日期)

Rob*_*son 5 r ggplot2 posixct

我想在 ggplot2 中散点图一个数字向量与白天(%H:%M)的关系。

我明白那个

as.POSIXct(dat$daytime, format = "%H:%M")
Run Code Online (Sandbox Code Playgroud)

是格式化时间数据的方法,但输出向量仍将包含日期(今天的日期)。因此,轴刻度将包括日期(3 月 22 日)。

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))
Run Code Online (Sandbox Code Playgroud)

绘图输出的图像

有没有办法完全摆脱日期,尤其是在情节轴上?(我在留言板上找到的所有信息似乎都是指旧版本的 ggplot,现在已经不存在 date_format 参数)

Uwe*_*Uwe 5

您可以为labels参数提供一个函数scale_x_datetime()或使用该date_label参数:

# 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"))
Run Code Online (Sandbox Code Playgroud)

编辑:或者,您可以使用更简洁的date_label参数(感谢aosmith建议)。

ggplot(dat, aes(daytime, y)) + geom_point() + 
  scale_x_datetime(date_label = "%H:%M")
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

  • 或者使用 `date_labels` 参数作为快捷方式,`date_labels = "%H:%M"`。 (2认同)