在ggplot中编辑悬停标签文本以显示百分比

时间:2021-07-18 05:11:59

标签: r ggplot2 tooltip r-plotly

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

这是一些可重现的代码:

app.config.from_object('project.config.configTest')

我的情节是什么样子

enter image description here

我想将悬停标签中的变量名称从 ## 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") 更改为“百分比”。

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

1 个答案:

答案 0 :(得分:0)

一种方法是预先计算要绘制的值,而不是使用 (..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

enter image description here