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

偶尔善良 提交于 2019-12-23 03:27:16

问题


I've found the following page instructing how to create custom hover text for plotly charts in R.

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

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.

Screenshot of the chart in RStudio:

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

回答1:


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



回答2:


I came here looking for same solution and the above one worked after some haggle but I ultimately found the right method later. Here it is:

Put your 'Size' variable inside marker=list()

So instead of

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

You can use

  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)) 

That worked for me.



来源:https://stackoverflow.com/questions/36596849/how-can-i-remove-the-size-line-in-the-hoverinfo-of-a-plotly-chart-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!