问题描述
我发现以下页面指示如何为R中的绘图图表创建自定义悬停文本.
I've found the following page instructing how to create custom hover text for plotly charts in R.
https://plot.ly/r/text-和注释/#custom-hover-text
这似乎完全符合我的要求,但是,当我将代码(见下文)复制到RStudio中并在本地运行时,我的hoverinfo中又多了一行,显示了size变量.
This seems to do exactly what I want, however when I copy the code (see below) into RStudio and run it locally I get an extra line in in my hoverinfo, showing the size variable.
RStudio中图表的屏幕截图:
Screenshot of the chart in RStudio:
如何在hoverinfo中删除此"wt(尺寸):1.835"行?
How can I remove this "wt (size): 1.835" line in hoverinfo?
library(plotly)
p <- mtcars %>%
plot_ly(x = disp, y = mpg, mode = "markers", color = cyl, size = wt,
hoverinfo = "text",
text = paste("Displacement = ", mtcars$disp, "Miles Per Gallon = ", mtcars$mpg)) %>%
layout(title ="Custom Hover Text")
p
推荐答案
我可以实现您想要的功能,但这很丑陋,而且确实有点hack.我对此并不感到骄傲,但是我们开始吧.
I can achieve what you want, but it's ugly, and really a bit of a hack. I'm not overly proud of this but here we go.
# Your plot
library(plotly)
p <- mtcars %>%
plot_ly(x = disp, y = mpg, mode = "markers", color = cyl, size = wt,
hoverinfo = "text",
text = paste("Displacement = ", mtcars$disp, "Miles Per Gallon = ", mtcars$mpg)) %>%
layout(title ="Custom Hover Text")
p
# Get the list for the plot
pp <- plotly_build(p)
# Pick up the hover text
hvrtext <- pp$data[[1]]$text
# Split by line break and wt
hvrtext_fixed <- strsplit(hvrtext, split = '<br>wt')
# Get the first element of each split
hvrtext_fixed <- lapply(hvrtext_fixed, function(x) x[1])
# Convert back to vector
hvrtext_fixed <- as.character(hvrtext_fixed)
# Assign as hovertext in the plot
pp$data[[1]]$text <- hvrtext_fixed
# Plot
pp
这篇关于如何在R中的Plotly图表的hoverinfo中删除尺寸线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!