简体   繁体   中英

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM