【问题标题】:Tooltip in percent stacked barchart百分比堆积条形图中的工具提示
【发布时间】:2021-05-05 09:11:39
【问题描述】:

我正在尝试以百分比堆积条形图格式化我的 ggplotly 工具提示。为此,我正在“aes”中编辑“文本”参数

   library(scales)
    library(tidyverse)
    library(plotly)
    library(ggplot2)
    library(shiny)
    
    #Define dataframe
    weeknum <- c(1,1,1,1,2,2,2,2,3,3,3,3)
    channel <- rep(c("a", "b"), 6)
    product <- c(rep("x",6), rep("y",6))
    data <- data.frame(weeknum, channel, product)
    
    # Define UI
    ui <- fluidPage(theme = shinytheme("flatly"),
                               mainPanel(
                                 h1("plot"),
                                 plotlyOutput(outputId = "plot_1", height = "800px")
                               ))
             
    # Define server function  
    server <- function(input, output) {
      output$plot_1 <- renderPlotly({
        p1 <- data %>% 
          ggplot(aes(x=weeknum, fill=channel, text = paste('share:', percent(..count..), "<br> channel", fill))) +
          geom_bar(position = "fill", stat ='count')+
          facet_grid(rows = vars(product))
        fig1 <- ggplotly(p1, tooltip = "text")
        fig1
      })
    }
    
    # Create Shiny object
    shinyApp(ui = ui, server = server)

所以这里我在工具提示中只得到了 count * 100%。我知道我需要将它除以条形的动态高度,因为在这个仪表板中我将使用一些过滤器。问题是我该怎么做? (..count..)/sum(..count..) 不起作用。

【问题讨论】:

  • 不是..count..吗?
  • 你能提供一个可重现的代码吗?
  • @RonakShah 我提供了一些可重现的代码
  • @StéphaneLaurent 我提供了可重现的代码。

标签: r ggplot2 shiny tooltip ggplotly


【解决方案1】:

由于您没有提供可重现的示例,我使用mtcars 数据集创建了一个。这就是我处理你的任务的方式。

library(ggplot2)
library(dplyr)

plot <- mtcars %>% 
  count(cyl, am, name = "count") %>%
  mutate(across(c(cyl, am), as.character)) %>% 
  ggplot(
    aes(x = cyl, fill= am, y = count,
        text = paste('share:', scales::percent(count/sum(count)), '<br>AM:', am)
        )
       ) + 
  geom_col(position = "fill")

plotly::ggplotly(plot, tooltip = "text") 
  

【讨论】:

  • 对我的解决方案@Michał89 有任何意见吗?
  • 很好,在这种情况下接受答案。
猜你喜欢
  • 1970-01-01
  • 2021-05-31
  • 2019-09-27
  • 1970-01-01
  • 2017-09-15
  • 2017-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多