6

我以半小时为间隔绘制时间序列数据,使用 geom_col() 显示每个间隔中计数的鸟类数量。ggplot2 绘制以x 轴刻度线为中心的每个条形图,但我需要每个条形图从每个刻度线的右侧开始。换句话说,我需要每个条跨越其相应的半小时间隔的宽度。

我在这些帖子中尝试了建议的解决方案,但没有运气:

下面是重现该问题的示例代码:

    ``` r
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union
library(ggplot2)
library(tidyverse)

df <- data.frame(
  date = c("2019-05-16", "2019-05-16", "2019-05-16", "2019-05-16", "2019-05-16", "2019-05-16", "2019-05-16", "2019-05-16"),
  time = c("16:30:00", "17:00:00", "17:30:00", "18:00:00", "18:30:00", "19:00:00", "19:30:00", "20:00:00"),
  count = c(5, 100, 14, 342, 59, 321, 44, 98),
  stringsAsFactors = FALSE)

datetime_df <- df %>% 
  mutate(time_stamp = paste(date, time) %>% as_datetime())

plot <- ggplot(datetime_df, aes(x = time_stamp, y = count)) +
  geom_col() +
  scale_x_datetime(breaks = scales::date_breaks("30 mins"), date_labels = "%H:%M",
                                    limits = c(as_datetime("2019-05-16 16:00:00"), 
                                               as_datetime("2019-05-16 20:30:00"))) +
  scale_y_continuous(expand = c(0,0), breaks = seq(0, 500, by = 50), limits = c(0,500))

reprex 包(v0.3.0)于 2020 年 10 月 1 日创建

这是生成的条形图

非常感谢您提供有关如何解决此问题的任何想法!

4

1 回答 1

4

您可以通过将 15 分钟添加到您的时间来轻松地模仿这一点:

plot <- ggplot(datetime_df, aes(x = time_stamp + minutes(15), y = count)) +
  geom_col() +
  scale_x_datetime(breaks = scales::date_breaks("30 mins"), date_labels = "%H:%M",
                                    limits = c(as_datetime("2019-05-16 16:00:00"), 
                                               as_datetime("2019-05-16 20:30:00"))) +
  scale_y_continuous(expand = c(0,0), breaks = seq(0, 500, by = 50), limits = c(0,500))
plot

在此处输入图像描述

要使刻度与柱的起点完全对齐,您需要设置width参数geom_col以匹配添加的分钟数。经过一些试验和错误,这似乎工作:

half_width_in_min = 13
plot <- ggplot(datetime_df, aes(x = time_stamp + minutes(half_width_in_min ), y = count)) +
  geom_col(width = 60 * 24 * 1.25 * half_width_in_min / 15) +
  scale_x_datetime(breaks = scales::date_breaks("30 mins"), date_labels = "%H:%M",
                                    limits = c(as_datetime("2019-05-16 16:00:00"), 
                                               as_datetime("2019-05-16 20:30:00"))) +
  scale_y_continuous(expand = c(0,0), breaks = seq(0, 500, by = 50), limits = c(0,500))
plot

在此处输入图像描述

于 2020-10-01T04:48:34.380 回答