如何删除R中Plotly图表的hoverinfo中的大小?

时间:2016-04-13 11:22:55

标签: r plotly

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

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

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

RStudio中图表的屏幕截图:

enter image description here

如何在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

2 个答案:

答案 0 :(得分:3)

我可以实现你想要的,但它很难看,而且真的有点黑客。我并不为此感到骄傲,但我们走了。

# 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

答案 1 :(得分:1)

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

将“尺寸”变量放在 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)) 

这对我有用。