我以半小时为间隔绘制时间序列数据,使用 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 日创建
非常感谢您提供有关如何解决此问题的任何想法!