r - 使用 scale_x_datetime() 设置限制会在 ggplot 中静默放置条形图
问题描述
主要目标:我正在尝试从具有一组 x 和 y 限制和比例的不同小标题构建一系列条形图,以便于跨图进行比较。x 轴是日期时间,y 轴是数字。我正在使用一组小标题中最具包容性的 x 和 y 范围来定义所有图的限制和比例。
挑战:当我向 scale_x_datetime() 添加限制以设置 x 轴范围时,ggplot 会静默删除我尝试绘制的数据,即使我的数据的 x 值在限制范围内。下面的代码显示了一个来自单个绘图的示例,以及我在使用 scale_x_datetime() 的限制参数时尝试(未成功)显示条形的一些事情。
library(dplyr)
library(tibble)
library(ggplot2)
library(lubridate)
example_dat <- tibble(
author_name = 'fname lname',
time_window = as_datetime('2019-12-07 00:00:00'),
time_read = 32.4
)
lims <- c(as_datetime('2019-12-01 00:00:00'),
as_datetime('2019-12-09 00:00:00'))
# when I plot without limits, the bar appears as expected
example_dat %>%
ggplot(aes(x = time_window, y = time_read)) +
geom_bar(stat = 'identity') +
scale_x_datetime() +
ylim(0, 35)
# when I plot with limits, the bar is silently dropped
example_dat %>%
ggplot(aes(x = time_window, y = time_read)) +
geom_bar(stat = 'identity') +
scale_x_datetime(limits = lims) +
ylim(0, 35)
# specifying breaks alongside the limits does not help, the bar is still silently dropped
example_dat %>%
ggplot(aes(x = time_window, y = time_read)) +
geom_bar(stat = 'identity') +
scale_x_datetime(limits = lims, breaks = as_datetime(c('2019-12-01 00:00:00',
'2019-12-02 00:00:00',
'2019-12-03 00:00:00',
'2019-12-04 00:00:00',
'2019-12-05 00:00:00',
'2019-12-06 00:00:00',
'2019-12-07 00:00:00',
'2019-12-08 00:00:00',
'2019-12-09 00:00:00'))) +
theme(axis.text.x = element_text(angle = 90)) +
ylim(0, 35)
# using as.POSIXct() instead of as_datetime() to define the limits does not help, the bar is still silently dropped
p_lims <- as.POSIXct(c('2019-12-01 00:00:00', '2019-12-09 00:00:00'),
tz = "GMT")
example_dat %>%
ggplot(aes(x = time_window, y = time_read)) +
geom_bar(stat = 'identity') +
scale_x_datetime(limits = p_lims) +
ylim(0, 35)
没有错误消息,我怀疑这是我对 ggplot 中刻度和日期交互方式的理解上的差距。这里的任何见解将不胜感激。
会话上下文:
R version 4.1.0 (2021-05-18)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Big Sur 11.5.2
attached base packages:
[1] stats graphics grDevices utils datasets
[6] methods base
other attached packages:
[1] lubridate_1.7.10 ggplot2_3.3.5 scales_1.1.1
[4] tibble_3.1.5 dplyr_1.0.7
谢谢
解决方案
推荐阅读
- php - PHP 创建循环来处理未知数量的传入 POST 数据
- javascript - jQuery没有检测到点击表中的链接
- mysql - SQL - 查找并删除两列具有重复值的行
- reactjs - deck.gl 层和 react-map-gl 覆盖的鼠标/触摸事件问题
- pug - 在 pugjs 中使用包含时缩进如何工作?
- android - 将预填充的 Sqlite DB 复制到 Android 应用程序数据库文件夹
- excel - Instr with If 语句
- return - 函数输出一个列表但返回 nil
- android - 如何通过wifi wampserver访问android上的localhost?
- api - Hyperwallet API,移除一个用户/一个转账方式