You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言中ggplotly与geom_dotplot悬停文本失效问题求助

解决方案:为geom_dotplot添加ggplotly悬停文本

问题根源

geom_dotplot依赖内置统计变换(stat_bindot)生成堆叠点,它会对原始数据做聚合计算后重新生成点坐标,导致ggplotly无法直接关联原始数据的text映射,最终出现悬停失效、样式错乱的问题。

方案1:手动计算点位置,用geom_point替代geom_dotplot

先提取geom_dotplot的统计计算结果,绑定原始数据的name字段,再用geom_point绘制,让ggplotly能正常识别悬停文本:

library(ggplot2)
library(plotly)

df <- data.frame(year  = c("2000", "2005", "2005", "2010", "2010", "2010"),
                 name = c("George", "Michael", "Bob", "James", "Will", "Fabrizio"))

# 获取geom_dotplot的统计计算坐标
dot_calculations <- ggplot_build(ggplot(df, aes(x = year)) + 
                            geom_dotplot(stackratio = 1, stackgroups = TRUE))$data[[1]]

# 按year排序原始数据,匹配统计结果的点顺序
df_sorted <- df[order(df$year), ]
dot_calculations$name <- df_sorted$name

# 用geom_point还原dotplot样式,添加悬停映射
p <- ggplot(dot_calculations, aes(x = x, y = y, text = name)) +
  geom_point(size = 10, fill = "darkgreen", shape = 21) +
  scale_x_continuous(breaks = c(1,2,3), labels = unique(df$year)) +
  theme_bw()

ggplotly(p, tooltip = "text")

方案2:用ggforce::geom_sina替代geom_dotplot

geom_sina可生成类似dotplot的堆叠点图,且原生支持ggplotly的悬停映射,无需额外处理:

library(ggplot2)
library(plotly)
library(ggforce)

df <- data.frame(year  = c("2000", "2005", "2005", "2010", "2010", "2010"),
                 name = c("George", "Michael", "Bob", "James", "Will", "Fabrizio"))

p <- ggplot(df, aes(x = year, y = 1, text = name)) +
  geom_sina(stackdir = "up", size = 10, color = "darkgreen") +
  theme_bw() +
  theme(axis.title.y = element_blank(),
        axis.text.y = element_blank(),
        axis.ticks.y = element_blank())

ggplotly(p, tooltip = "text")

两种方案都能保留原dotplot的视觉样式,同时实现鼠标悬停显示对应name字段的功能。

内容的提问来源于stack exchange,提问作者Reed Cooley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 15:27:21