Tim Sanders Tim Sanders - 3 months ago 41
R Question

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:

enter image description here

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

mal mal
Answer

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