当它是日期时如何在ggplotly中显示正确的水平轴

How to show correct horizontal axis in ggplotly when it is a date

我很确定这是一个错误,希望在短期内找到解决方法。

library(tidyverse)
library(plotly)
d <- tibble(
  date = as.Date("2012-01-01") + 0:5000,
  y = rnorm(5001)
)

p <- ggplot(d, aes (x = date, y = y)) + 
  geom_point() 

p

ggplotly(p)

这是由 ggplot2 渲染的 p

数据正确到 2025 年 9 月。

但这里是 plotly 渲染的:

所有数据都在那里,工具提示正确地将图表右侧的点标记为 2025 年 9 月,但根据 x 轴,它们更像是 2022 年(事实上,它看起来只是转置四五年后)。

关于 a) 如果这是一个错误或者我在做一些愚蠢的事情以及 b) 有什么解决方法的建议吗?

编辑以添加 sessionInfo()

> sessionInfo()
R version 3.6.3 (2020-02-29)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 16299)

Matrix products: default

locale:
[1] LC_COLLATE=English_Australia.1252  LC_CTYPE=English_Australia.1252    LC_MONETARY=English_Australia.1252
[4] LC_NUMERIC=C                       LC_TIME=English_Australia.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] plotly_4.9.2    forcats_0.5.0   stringr_1.4.0   dplyr_0.8.5     purrr_0.3.3     readr_1.3.1    
 [7] tidyr_1.0.2     tibble_2.1.3    ggplot2_3.3.0   tidyverse_1.3.0

loaded via a namespace (and not attached):
 [1] tidyselect_1.0.0  haven_2.2.0       lattice_0.20-40   colorspace_1.4-1  vctrs_0.2.4       generics_0.0.2   
 [7] htmltools_0.4.0   viridisLite_0.3.0 yaml_2.2.1        rlang_0.4.5       pillar_1.4.3      glue_1.3.1       
[13] withr_2.1.2       DBI_1.1.0         dbplyr_1.4.2      modelr_0.1.6      readxl_1.3.1      lifecycle_0.2.0  
[19] munsell_0.5.0     gtable_0.3.0      cellranger_1.1.0  rvest_0.3.5       htmlwidgets_1.5.1 labeling_0.3     
[25] crosstalk_1.1.0.1 Cairo_1.5-11      fansi_0.4.1       broom_0.5.5       Rcpp_1.0.3        scales_1.1.0     
[31] backports_1.1.5   jsonlite_1.6.1    farver_2.0.3      fs_1.3.2          hms_0.5.3         digest_0.6.25    
[37] stringi_1.4.6     grid_3.6.3        cli_2.0.2         tools_3.6.3       magrittr_1.5      lazyeval_0.2.2   
[43] crayon_1.3.4      pkgconfig_2.0.3   data.table_1.12.8 xml2_1.2.5        reprex_0.3.0      lubridate_1.7.4  
[49] assertthat_0.2.1  httr_1.4.1        rstudioapi_0.11   R6_2.4.1          nlme_3.1-145      compiler_3.6.3  

事实证明这是 plotly 和最新版本的 ggplot2 之间的问题。如果我从 ggplot2 3.3.0 恢复到 3.2.1,问题就会自行解决:

devtools::install_version("ggplot2", version = "3.2.1", repos = "http://cran.us.r-project.org")

library(tidyverse)
library(plotly)

d <- tibble(
  date = as.Date("2012-01-01") + 0:5000,
  y = rnorm(5001)
)

p <- ggplot(d, aes (x = date, y = y)) + 
  geom_point() 

ggplotly(p)

所以解决方法是暂时坚持 ggplot2 3.2.1 和 post plotly 的错误报告(我不认为我们可以称它为 ggplot2 错误,因为它只出现在 plotly 的解释中比例)。