【问题标题】:In ggplot2/plotly ,when I use `geom_bar(stat='identity',position='fill')`,how to change number tip to percent format在 ggplot2/plotly 中,当我使用 `geom_bar(stat='identity',position='fill')` 时,如何将数字提示更改为百分比格式
【发布时间】:2022-01-13 01:08:19
【问题描述】:

在 R/ggplot2 中,当我使用geom_bar(stat='identity',position='fill') 时, “销售”提示显示“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)

【问题讨论】:

    标签: ggplot2 plotly ggplotly


    【解决方案1】:

    一种选择(也许是最简单的一种)是手动计算您的百分比,而不是使用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")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-26
      • 2018-10-05
      • 1970-01-01
      • 2022-01-06
      • 2018-03-17
      相关资源
      最近更新 更多