I've written a function to create a plot with data that changes based on a filter input, below is a simplified reprex:
library(tidyverse)
library(plotly)
one<- as.numeric(NA)
two<- 25
three<- 35
four<- 40
five<- 0
dat<- data.frame(one, two, three, four, five)
get_plot <- function(x, a){
data<- x[, a]
p<- data %>%
pivot_longer(everything(), names_to="variable", values_to="value") %>%
ggplot(aes(x = reorder(variable, value), y = value, fill = variable, text = paste0(value*100, "%"))) +
geom_bar(stat = "identity",position = "dodge")+
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank(),
axis.title.y=element_blank(),
legend.position = "none")+
coord_flip()
ggplotly(p, tooltip = c("text")) %>% config(displaylogo = FALSE,
modeBarButtons = list(list("toImage")))
}
get_plot(dat, a= c(1:5))
Depending on the filter sometimes I end up with a chart with categories that don't have values in them because the filtered data frame I feed the function ends up looking like dat from my reprex. How do I exclude categories from appearing on the plot when the value is 0 or NA?