主要目標:我試圖從不同的小標題構建一系列條形圖,其中包含一組 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
謝謝
uj5u.com熱心網友回復:
它就在那里,它只是 veeeeeeeery 狹窄!
我認為在這種情況下 ggplot 將您的示例解釋為發生在 1 秒內,因為這是您資料的解析度,但您的時間范圍是 8 天 x 24 小時 x 60 mx 60 s = 691,200 秒長。
要使欄“一天”變寬:
example_dat %>%
ggplot(aes(x = time_window, y = time_read))
geom_bar(stat = 'identity', width = 60*60*24)
scale_x_datetime(limits = lims)
ylim(0, 35)

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/313693.html
