首页 > 解决方案 > 如何使 scale_y_reverse 与 scale_y_time 一起工作

问题描述

我在 y 轴上绘制HH :MM:SS ,在 x 轴上绘制YYYY:MM,但是在尝试将scale_y_reversescale_y_time一起使用时遇到问题。

样本数据如下:

library(hms)
library(ggplot2)

df_stack <- data.frame(yr_mn = rep(c("2020-01", "2020-02", "2020-03", "2020-04"),2),
                   timept_type = c(rep("A",4),rep("B",4)),
                   timept = as_hms(c("08:00:00", "09:10:00", "11:05:30", "10:45:00", "09:30:10", "10:00:00", "11:25:00", "08:40:00")))


df_stack %>%
  ggplot(., aes(x=yr_mn, y=timept, color=timept, fill=timept)) +
  geom_point() +
  geom_line(aes(group=1))+
  facet_wrap(vars(timept_type), scales="free", ncol=2) +
  scale_y_time(limits = c(as.POSIXct(as_hms("07:00:00")), as.POSIXct(as_hms("11:30:00")))) +
  scale_y_reverse() # this cause the y-axis labels to no longer be in hh:mm:ss format

如果我注释掉最后一行scale_y_reverse()那么图表看起来很好,但如果我包含它,scale_y_reverse似乎将HH:MM:SS转换为秒。我不知道这是我做错了什么,还是scale_y_time中有内置方法来解决这个问题。谢谢!

标签: rggplot2tidyverse

解决方案


您可以省略scale_y_time和提供函数来scale_y_reverse生成标签和中断。

df_stack %>%
  ggplot(aes(yr_mn, timept, color = timept, fill = timept)) +
  geom_point() +
  geom_line(aes(group = 1)) +
  facet_wrap(vars(timept_type), scales = "free", ncol = 2) +
  scale_y_reverse(labels = function(x) as_hms(x),
                  breaks = seq(as.numeric(as_hms("07:00:00")), 
                               as.numeric(as_hms("11:30:00")),
                               1800))

结果:

在此处输入图像描述


推荐阅读