Search code examples
rplotlyr-plotly

How to set different text and hoverinfo text


I am working with the plotly package, and I cannot find a way to display different things on the chart itself and in the hoverinfo. Here is an example of a barchart:

library(plotly)
library(dplyr)

data(iris)

df <- iris %>%
  group_by(Species) %>%
  summarise(n = n(),
            avg = mean(Sepal.Length))

p1 <- plot_ly(data = df,
             x = ~Species,
             y = ~n,
             type = "bar",
             text = ~paste("Species :", Species,
                           "<br> Avg :", avg),
             textposition = "auto",
             hoverinfo = "text")

From this code I get this: enter image description here And I would like to display the frequency (n) value in each bar instead of the same thing as the hoverinfo.

I have been looking at this thread but the solution described is too complicated for me and I think there must be an easier way to solve this issue.


Solution

  • Something like this?

    p1 <- plot_ly(data = df,
                  x = ~Species,
                  y = ~n,
                  type = "bar",
                  text = ~n,
                  textposition = "auto",
                  hoverinfo = "text",
                  hovertext = paste("Species :", df$Species,
                                    "<br> Avg :", df$avg))
    

    enter image description here