I'm trying to update the hover labels in my plot to show "Percentage: XX%" (where XX is the value of the percentage of each bar).
Here is some reproducible code:
## 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")
What my plot looks like
I would like to change the variable name in the hover label from (..count..)*100/sum(..count..)
to "Percentage".
Any help would be greatly appreciated, I've been struggling with this for a while ahaha
One way would be to pre-calculate the values to plot instead of using (..count..)*100/sum(..count..)
. This would also need to change geom_bar
to 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