Search code examples
rggplot2r-plotlyggplotly

how to show variable name on barchart tooltip when bars are ordered by value in ggplotly


I have a ggplot which the bars are ordered by value and rendered by plotly::ggplotly to make it interactive. However, on the graph, hovering over the bars show the variable name as reorder(category, n).

So the tootips show:

    reorder(category, n): xxx
    n: xxx
    subCategory: xxx

What I need on tooltip is like:

category: xxx
subCategory: xxx
n: xxx

Does anyone know how I can fix that? I have no clue what to do with it.....

Below is my code for the plot:

library(dplyr)
library(ggplot2)
library(plotly)

df = data.frame(category=c('A','A', 'B', 'B','C','C', 'D','D'),
                subCategory = c('Y', 'N', 'Y', 'N', 'Y', 'N','Y', 'N'),
                n=c(120, 22, 45, 230, 11, 22, 100, 220))
df %>% 
  ggplot(aes(x=category, y=n, fill=subCategory))+
  geom_bar(stat='identity')

g=df %>% 
  ggplot(aes(x=reorder(category, n), y=n, fill=subCategory))+
  geom_bar(stat='identity')

ggplotly(g)

Solution

  • One possible solution will be to not use reorder in ggplot but instead reorder your x axis before passing it in ggplot such as:

    g=df %>% arrange(n) %>% 
      mutate(category = factor(category, unique(category))) %>%
      ggplot(aes(x=category, y=n, fill=subCategory))+
      geom_bar(stat='identity')+
      labs(x = "Category")
    
    ggplotly(g)
    

    An another option will be to set arguments in ggplot to be use in the tooltip argument of ggplotly such as:

    g=df %>% 
      ggplot(aes(x=reorder(category, n), y=n, fill=subCategory, 
                 text = paste("category:", category), text2 = n, text3 = subCategory))+
      geom_bar(stat='identity')+
      labs(x = "Category")
    
    ggplotly(g, tooltip = c("text","text2","text3"))
    

    Does it answer your question ?