flexdashboard中ggplotly结合geom_vline不显示竖线求助
问题:ggplotly搭配geom_vline时,Excel导入的日期无法显示竖线
手动构造的事件日期(event tibble)能正常生成带蓝色虚线竖线的交互式图表,但从Excel导入并转换为相同POSIXct格式的fecha.evento tibble,无法显示竖线。两者数据结构一致,已尝试修改变量类型、调整代码,问题仍未解决。
正常显示的代码
library(openair) library(tidyverse) library(plotly) aq <- importAURN(site = c("my1", "nott"), year = 2000, pollutant = c("nox", "no2", "o3")) aq <- aq %>% pivot_longer(cols = 2:4, names_to = "Parameter", values_to = "Value") event <- tibble(date = c("2000-03-23 11:00:00","2000-05-29 11:40:00","2000-08-22 12:00:00")) event$date <- as.POSIXct(event$date,format="%Y-%m-%d %H:%M", tz = "UTC") b <- ggplot(aq, aes(x = date, y = Value, colour = site, group = site)) + geom_line() + geom_vline(data = event , aes(xintercept = as.numeric(date)), linetype = 2, colour = "blue", show.legend = TRUE) + theme_bw() + facet_grid(Parameter ~ ., scales = "free") ggplotly(b,dynamicTicks = TRUE) %>% layout(legend = list(orientation = "h", y = -0.2))
无法显示竖线的代码
fecha.evento <- tibble(date = as.character(evento.q$`Toma conocimiento`)) fecha.evento$date <- as.POSIXct(fecha.evento$date,format="%Y-%m-%d %H:%M:%S", tz = "UTC") a <- ggplot(quintero, aes(x = date, y = dato_val_ug, colour = Ubicación, group = Ubicación)) + geom_line() + geom_vline(data = fecha.evento, aes(xintercept = as.numeric(date)), linetype = 2, colour = "blue", show.legend = TRUE) + theme_bw() + facet_grid(Parámetro ~ ., scales = "free") ggplotly(a,dynamicTicks = TRUE) %>% layout(legend = list(orientation = "h", y = -0.2))
数据结构
> str(event) tibble [3 × 1] (S3: tbl_df/tbl/data.frame) $ date: POSIXct[1:3], format: "2023-03-23 11:00:00" "2023-05-02 11:40:00" "2023-04-22 12:00:00" > str(fecha.evento) tibble [10 × 1] (S3: tbl_df/tbl/data.frame) $ date: POSIXct[1:10], format: "2023-03-23 11:00:00" "2023-03-29 11:40:00" "2023-03-30 12:00:00" "2023-03-31 10:30:00" ...
排查方向与解决建议
- 检查日期范围匹配:用
range(quintero$date)和range(fecha.evento$date)对比,确认事件日期是否在主数据的x轴区间内,超出范围的竖线不会显示。 - 强制时区一致性:用
lubridate::force_tz(fecha.evento$date, tzone = "UTC")重置时区,确保和quintero$date完全一致,避免隐含时区差异。 - 移除
as.numeric()转换:将geom_vline的aes(xintercept = as.numeric(date))改为aes(xintercept = date),直接使用POSIXct类型更稳定。 - 排查分面影响:先去掉
facet_grid测试竖线是否显示,若正常再检查各分面的时间范围是否包含事件日期。 - 验证日期转换有效性:用
head(fecha.evento$date)查看转换结果,确认无NA值,若存在则调整日期格式字符串匹配Excel导出的格式。
内容的提问来源于stack exchange,提问作者Camilo Montes
相关产品推荐
相关产品推荐

