如何删除 R 中 Plotly 图表的 hoverinfo 中的尺寸线?

How can I remove the size line in the hoverinfo of a Plotly chart in R?

我找到了以下页面,指导如何在 R 中为绘图图表创建自定义悬停文本。

https://plot.ly/r/text-and-annotations/#custom-hover-text

这似乎完全符合我的要求,但是当我将代码(见下文)复制到 RStudio 并在本地 运行 时,我在 hoverinfo 中多了一行,显示了 size 变量。

RStudio 中的图表截图:

如何删除 hoverinfo 中的 "wt (size): 1.835" 行?

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。我对此并不过分自豪,但我们开始吧。

# 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

我来这里寻找相同的解决方案,上面的解决方案经过一番讨价还价后有效,但后来我最终找到了正确的方法。这是:

将你的 'Size' 变量放入 marker=list()

所以而不是

 plot_ly(x = disp, y = mpg, mode = "markers", color = cyl, size = wt, 
          hoverinfo = "text",
          text = paste("Displacement = ", mtcars$disp, "Miles Per Gallon = ", mtcars$mpg)) 

可以使用

  plot_ly(x = disp, y = mpg, mode = "markers", color = cyl, marker=list(size=wt), 
              hoverinfo = "text",
              text = paste("Displacement = ", mtcars$disp, "Miles Per Gallon = ", mtcars$mpg)) 

这对我有用。