Search code examples
ggplot2plotlyggplotly

In ggplot2/plotly ,when I use `geom_bar(stat='identity',position='fill')`,how to change number tip to percent format


In R/ggplot2 ,when I use geom_bar(stat='identity',position='fill'), the 'sales' tip show '0.80000',how to change it to '80.0%' ? (I know mutate a new variable use scales::percent(sales),can work in geom_point)

library(tidyverse)
library(plotly)
test_data <- data.frame(category=c('A','B','A','B'),
                        sub_category=c('a1','b1','a2','b2'),
                        sales=c(1,2,4,5))

p <- test_data %>% 
  ggplot(aes(x=category,y=sales,
                              fill=sub_category))+
  geom_bar(stat='identity',position='fill') 

ggplotly(p)

enter image description here


Solution

  • One option (and perhaps the easiest one) would be to compute your percentages manually instead of making use of position = "fill" and create the tooltip manually via the text aesthetic which makes it easy to style the numbers, ... as you like:

    library(plotly)
    
    test_data <- data.frame(
      category = c("A", "B", "A", "B"),
      sub_category = c("a1", "b1", "a2", "b2"),
      sales = c(1, 2, 4, 5)
    )
    
    test_data <- test_data %>%
      group_by(category) %>%
      mutate(pct = sales / sum(sales))
    
    p <- test_data %>%
      ggplot(aes(x = category, y = pct, fill = sub_category)) +
      geom_col(aes(text = paste0(
        "category: ", category, "<br>",
        "sub_category: ", sub_category, "<br>",
        "sales: ", scales::percent(pct)
      )))
    
    ggplotly(p, tooltip = "text")
    

    enter image description here