ggplotly转换ggplot时丢失低引用量观测值的解决方法咨询
问题原因
该现象是ggplot转ggplotly的默认处理逻辑导致:geom_segment生成的零长度线段(即start等于end的线段,对应被引量极低、y轴方向无长度差的论文条目),会被plotly判定为无效几何元素自动过滤,而ggplot原生渲染会保留这类零长度线段的填充块,因此二者展示效果不一致。
可行解决方案
以下两种方案均可实现所有数据正常展示:
方案1:添加极小偏移量(改造成本最低)
仅需对yend参数做极小数值偏移,避免出现零长度线段即可,偏移量远小于正常被引量的数值差,视觉上完全不会影响原有展示效果,修改后代码如下:
library(tidyverse) library(plotly) download.file("https://raw.githubusercontent.com/luizaandrade/dec-bibliometrics-dashboard/main/citations.rds", "data.rds", method = "curl") data <- readRDS("data.rds") graph <- data %>% ggplot() + geom_segment( aes(x = year_scholar, xend = year_scholar, y = start, # 核心修改:给end加1e-3的极小偏移,避免零长度线段 yend = ifelse(end == start, end + 1e-3, end), color = year_id, text = paste0(title, "<br>", all_authors, "<br>", journal, "<br>", "Citations: ", cites)), size = 10, lineend = "butt") ggplotly(graph, tooltip = "text")
方案2:改用geom_tile绘制(渲染效果更稳定)
你当前的绘图场景本质是按年份绘制不同高度的垂直色块,用geom_tile更适配,也不会出现零长度元素被过滤的问题,修改后代码如下:
library(tidyverse) library(plotly) download.file("https://raw.githubusercontent.com/luizaandrade/dec-bibliometrics-dashboard/main/citations.rds", "data.rds", method = "curl") data <- readRDS("data.rds") graph <- data %>% # 计算色块的中心y坐标和高度 mutate(y_mid = (start + end)/2, y_height = end - start + 1e-3) %>% ggplot() + geom_tile( aes(x = year_scholar, y = y_mid, height = y_height, width = 0.9, fill = year_id, color = year_id, text = paste0(title, "<br>", all_authors, "<br>", journal, "<br>", "Citations: ", cites)), size = 0.1) ggplotly(graph, tooltip = "text")
内容的提问来源于stack exchange,提问作者Luíza Andrade
相关产品推荐
相关产品推荐

