删除 geom_bar 中的空白类别
Remove blank categories in geom_bar
我编写了一个函数来创建图表,其中的数据会根据过滤器发生变化
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))
根据过滤器的不同,有时我会得到一个图表,其中的类别没有值,如下图所示。当类别没有值时,如何排除类别出现在图中? **** 编辑以制作更简化的代表****
更新,在今天早上仔细考虑并进行了更多谷歌搜索和尝试之后,我找到了解决方案。我将这些 select 语句插入到函数中,它得到了我想要的!
p<- data %>%
select(where(~!any(is.na(.)))) %>%
select(where(~!any(.== 0))) %>%
我编写了一个函数来创建图表,其中的数据会根据过滤器发生变化
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))
根据过滤器的不同,有时我会得到一个图表,其中的类别没有值,如下图所示。当类别没有值时,如何排除类别出现在图中? **** 编辑以制作更简化的代表****
更新,在今天早上仔细考虑并进行了更多谷歌搜索和尝试之后,我找到了解决方案。我将这些 select 语句插入到函数中,它得到了我想要的!
p<- data %>%
select(where(~!any(is.na(.)))) %>%
select(where(~!any(.== 0))) %>%