【问题标题】:howto get ggplot facet-wrap working with x-axis scale in hh:mm only (no dates)如何让 ggplot facet_wrap 仅在 hh:mm 中使用 x 轴刻度(无日期)
【发布时间】:2019-06-01 07:50:26
【问题描述】:

我正在努力获得一个包含两件事的 ggplot 图表:

  • 将数据分隔到每个日期的 facet-wrap
  • 保持 x 轴刻度仅相对于小时和分钟 (HH:MM) ,并使每个分面环绕图之间的 x 轴刻度保持彼此相同的宽度。 (即 10:00 出现在每个方面图表的相同位置)
  • 这些图表的时间段少于 24 小时,仅涵盖上午 9 点至下午 4 点

为了在 x 轴上获得可读性好的标签,我所做的一切都会导致连续的“时间”变量在其中有巨大的差距,这似乎是因为日期也包含在幕后。

这是我当前的代码,可以生成我非常需要的 facet-wrap,但 x 轴不可读。

ggplot(mydata2, aes(x=time, y=pending, color=server, group=date)) +
  geom_point() +
  facet_wrap(~ date)
> class(mydata2$time)
[1] "character"

我已经尝试过 hms 库。但 ggplot 似乎不知道如何处理它。

mydata2$time2 <- lubridate::hms(mydata2$time)

mydata2$time2
   [1] "14H 5M 23S"  "14H 5M 23S"  "14H 5M 42S"  "14H 5M 42S"  "14H 6M 24S"  "14H 6M 24S" 
   [7] "14H 6M 42S"  "14H 6M 42S" .... etc.

但尝试绘制此图表失败,下面只会生成一个空白图表...

ggplot(mydata2, aes(x=time2, y=pending, color=server, group=tradedate)) +
  geom_point() +
  facet_wrap(~ tradedate)

Warning messages:
1: Removed 7390 rows containing missing values (geom_point). 

我怎样才能实现上面列出的 2 个目标?

【问题讨论】:

  • 虽然根据您的问题我无法辨别您的实际需求,但我想提供this link,希望它能带您找到最终解决方案。
  • 感谢 Roman,进一步思考其他要求之一是每个 facet wrap 图表仅显示上午 9 点到下午 4 点之间的时间段。也许这就是 facet wrap 的自动格式化失败的地方?
  • 无数据,无图,部分代码。抱歉,我不能再发表任何评论了。

标签: r ggplot2 facet-wrap


【解决方案1】:

我无法重现该问题。你看看这是否有帮助?否则,请将数据示例发布为代码。

set.seed(1234)
df <-
  tibble(
    timestamp = seq(
      ymd_hms("2019-01-01 00:00:00"), 
      ymd_hms("2019-01-04 00:00:00"), by = "1000 sec"
    ),
    tradedate = as.Date(timestamp),
    hms = hms::hms(as.numeric(timestamp - floor_date(timestamp, "1 day"), unit="secs"))
  ) %>% 
  mutate(
    pending = sample(11:20, size = n(), replace = TRUE)
  ) 


ggplot(df, aes(x = hms, y = pending, color = factor(tradedate))) +
  geom_point() +
  facet_grid(tradedate~.)

【讨论】:

    猜你喜欢
    • 2021-03-05
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 1970-01-01
    • 2021-04-08
    • 2022-01-08
    相关资源
    最近更新 更多