在 ggplot2/plotly 中,当我使用 `geom_bar(stat='identity',position='fill')` 时,如何将数字提示更改为百分比格式

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

在R/ggplot2中,当我使用geom_bar(stat='identity',position='fill')时, 'sales' 提示显示 '0.80000',如何将其更改为 '80.0%'? (我知道改变一个新变量使用 scales::percent(sales),可以在 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)

一个选项(也许是最简单的选项)是手动计算您的百分比而不是使用 position = "fill" 并通过 text 美学手动创建工具提示,这样可以轻松设置样式数字,...如你所愿:

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")