Search code examples
rggplot2plotlyscatter-plotr-plotly

How can I see the values of a variable that I specified with "size = " in a plotly plot using R (package: plotly)


I want to produce an interactive plot using the plotly package in R. I want a scatter plot where each point is "sized" according to their continuous values. My plot does show the sized points, but it does not show me which value they are when I hover on them. The reproducible code:

library(plotly)
plot_ly(data = mtcars,
        x = ~ wt, y = ~ mpg, color = ~factor(cyl),
        mode = "markers", type = "scatter", size = ~hp)
Warning messages:
1: `line.width` does not currently support multiple values. 
2: `line.width` does not currently support multiple values. 
3: `line.width` does not currently support multiple values.

What I want is when I go to a specific point, I want to interactively see which "hp" value it has apart from its size.


Solution

  • You can add this with , text = ~hp in to the plot_ly window and format it using this link

    eg

    library(plotly)
    plot_ly(data = mtcars,
            x = ~ wt, y = ~ mpg, color = ~factor(cyl),
            mode = "markers", type = "scatter", size = ~hp, 
            text = ~hp, 
            hovertemplate = paste("Values: %{x}, %{y}<br>", 
                                  "Size: %{text}")
    )
    

    enter image description here