Search code examples
rggplot2plotlyr-plotly

R Plotly how to use both position dodge and format hover text


I want to create a plotly object that is 1.) position dodged on the x-axis and 2.) has formatted text the way I want it. I am able to fulfil each condition separately but am unable to do them both at the same time.

Here I have a plotly plot that is properly position dodged

library(tidyverse)
library(plotly)

df <- data.frame(
  x = c(1, 2, 3, 4),
  y = runif(8, 5, 10),
  cat = c("a", "a", "a", "a", "b", "b", "b", "b")
)

p <- ggplot(df, groups = cat) +
  geom_point(aes(x = x, y = y, color = cat),
             position = position_dodge(width = 0.3))

ggplotly(p)

And here I have a plotly plot with formatted hover text

plot_ly(df, x = ~x, 
        y = ~y, 
        type = 'scatter', 
        mode = 'markers',
        color = ~cat,
        hoverinfo = 'text',
        text = ~paste('</br> X is ', x,
                      '</br> Y is ', y,
                      '</br> Cat is ', cat
        )
)

How can I combine these two ideas so that I have a plot that is position dodged and also with manually formatted hover text?


Solution

  • You could pass your customized hover text via the text "aesthetic" and adding argument tooltip="text" to your call of ggplotly:

    library(tidyverse)
    library(plotly)
    
    df <- data.frame(
      x = c(1, 2, 3, 4),
      y = runif(8, 5, 10),
      cat = c("a", "a", "a", "a", "b", "b", "b", "b")
    )
    
    p <- ggplot(df, groups = cat) +
      geom_point(aes(x = x, y = y, color = cat, 
                     text = paste('</br> X is ', x, '</br> Y is ', y, '</br> Cat is ', cat)), 
                 position = position_dodge(width = 0.3))
    
    ggplotly(p, tooltip = "text")