【问题标题】:Edit hover label text in ggplot to show percentage在ggplot中编辑悬停标签文本以显示百分比
【发布时间】:2021-07-18 05:11:59
【问题描述】:

我正在尝试更新绘图中的悬停标签以显示“百分比:XX%”(其中 XX 是每个条形的百分比值)。

这是一些可重现的代码:

## Data from https://data.melbourne.vic.gov.au/People/Indicators-of-quality-of-life-and-city-services-by/e6er-4cb3

library(dplyr)
library(ggplot2)
library(plotly)
data <- read.csv("Indicators_of_quality_of_life_and_city_services_by_year.csv")
head(data)
#data$Indicator.Theme
#data$Type
data <- data[,c("Indicator.Theme", "Type")]
data

que_code <- data %>% mutate(newcat = Indicator.Theme)
response <- que_code$newcat
category <- factor(que_code$Type)
textfill= "Type"

plott <- ggplot(que_code, aes(x=response, fill=category)) +
  geom_bar(position="dodge", width = 0.5, aes(y = (..count..)*100/sum(..count..), label="Percentage")) + labs(fill= textfill) + xlab("Response to survey questions")+ylab("Percentage")+
  scale_fill_manual(values = c("#ae3cc6", "#9630a8", "#842791", "#6d1b73", "#780e55",
                               "#7e0643", "#820036", "#a11635", "#bb2835", "#d93d35",
                               "#e74735", "#fd5634", "#fe7c5b", "#ffa182"), drop=FALSE) + scale_x_discrete(drop=FALSE)+
  theme(axis.text.x = element_text(size = 10, angle = 30))

plott <- ggplotly(plott, tooltip="y")

我的情节是什么样子的

我想将悬停标签中的变量名称从(..count..)*100/sum(..count..) 更改为“百分比”。

任何帮助将不胜感激,我已经为此苦苦挣扎了一段时间啊哈哈

【问题讨论】:

    标签: r ggplot2 tooltip r-plotly


    【解决方案1】:

    一种方法是预先计算要绘制的值,而不是使用(..count..)*100/sum(..count..)。这也需要将geom_bar 更改为geom_col

    library(dplyr)
    library(ggplot2)
    library(plotly)
    
    plott <- que_code %>%
      count(Type, Indicator.Theme, name = 'Percentage') %>%
      mutate(Percentage = prop.table(Percentage) * 100) %>%
      ggplot(aes(x=Indicator.Theme, fill=Type)) +
      geom_col(position="dodge", width = 0.5, aes(y = Percentage)) + 
      labs(fill= textfill) + 
      xlab("Response to survey questions")+
      ylab("Percentage") +
      scale_fill_manual(values = c("#ae3cc6", "#9630a8", "#842791", "#6d1b73", "#780e55",
                                   "#7e0643", "#820036", "#a11635", "#bb2835", "#d93d35",
                                   "#e74735", "#fd5634", "#fe7c5b", "#ffa182"), drop=FALSE) + 
      scale_x_discrete(drop=FALSE)+
      theme(axis.text.x = element_text(size = 10, angle = 30))
    
    plott <- ggplotly(plott, tooltip="y")
    plott
    

    【讨论】:

      猜你喜欢
      • 2021-07-27
      • 2023-04-02
      • 2014-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-28
      相关资源
      最近更新 更多