R语言如何自定义ggplotly生成的plotly交互式悬停弹窗?
问题说明
ggplotly将ggplot对象转换为交互式plotly对象时,会默认把映射到坐标轴的字符型分类变量转换为底层数值位置索引,这就是悬停提示框中model字段显示1、2等数字,而非预期A、B值的原因。plotly完全支持自定义悬停提示窗口的展示内容、字段和格式。
解决方案
方案1:绘图时自定义悬停文本(推荐)
在ggplot的aes()映射中新增text属性自定义悬停展示内容,调用ggplotly()时指定tooltip参数仅展示自定义文本,同时建议提前将分类变量转为因子固定顺序,代码如下:
library(ggplot2) library(plotly) df <- data.frame (model = c("A", "A","B","B"), year = c("2022","2021","2022","2021"), sale = c(350,170,300,150), change = c(180,NA,150,NA), percent = c(105.8,NA,100,NA), info = c("180, 105.8%",NA,"300,100%",NA) ) # 提前将model转为因子,固定分类排序 df$model <- as.factor(df$model) plot <- ggplot(df, aes(fill=year, y=model, x=sale, # 自定义悬停展示内容,<br>是plotly提示框的换行符 text = paste0("model: ", model, "<br>year: ", year, "<br>sale: ", sale))) + geom_bar(position="dodge", stat="identity") + geom_text(aes(label=info, x=1.11*max(sale)), fontface='bold')+ xlim(0, 1.2*max(df$sale)) + theme(legend.position="bottom")+ labs(fill = " ")+ scale_fill_brewer(palette = "Paired") # 指定tooltip仅展示自定义的text字段 ggplotly(plot, tooltip = "text")
你可以根据需求在text的拼接内容中新增、删除要展示的字段,自由调整提示框的显示格式。
方案2:转换后修改plotly对象
如果不想调整原有ggplot绘图代码,可以在生成ggplotly对象后,直接修改条形对应trace的悬停文本,替换错误的数值为正确分类值:
# 生成默认的交互式图表 p <- ggplotly(plot) # 遍历所有trace,仅修改条形图层的悬停文本 for (i in seq_along(p$x$data)) { if (!is.null(p$x$data[[i]]$type) && p$x$data[[i]]$type == "bar") { # 替换文本中model后的数字为正确分类值 bar_year <- unique(gsub(".*year: (\\d+).*", "\\1", p$x$data[[i]]$text))[1] model_match <- unique(df$model[df$year == bar_year]) p$x$data[[i]]$text <- gsub("model: \\d+", paste0("model: ", model_match), p$x$data[[i]]$text) } } # 输出修正后的图表 p
内容的提问来源于stack exchange,提问作者user18937485
相关产品推荐
相关产品推荐

