如何在使用 tidyr 重塑数据后从 facet_wrap 中删除一个方面类别

How to remove one facet category from facet_wrap after using tidyr to reshape data

我正在尝试绘制一些数据并查看下面的可复制示例,从相关库开始

library(ggplot2)
library(tidyr)
library(scales)
library(dplyr)

以及随机数据集的创建见下文:

data <- data.frame(replicate(3, sample(0:100, 100, rep=TRUE)))
data$Place <- sample(c("PlaceA", "PlaceB","PlaceC"), size = nrow(data), prob = c(0.76, 0.14, 0.10), replace = TRUE)
data$Preference <- sample(c("Strong", "Medium","Low"), size = nrow(data), replace = TRUE)
data$Risk <- sample(c("Yes","No"), size = nrow(data), replace = TRUE)
colnames(data) <- c("A","B","C","Place","Preference","Risk")
rownames(data) <- NULL

在这一步之后,我尝试使用 tidyr 包获取不同形状的数据

data_long <- tidyr::gather(data, key = type_col, value = categories, -c("A","B","C","Place","Preference"))

然后我希望按地点绘制出对风险表示同意的受访者比例——请参阅下面的代码以实现视觉输出

data_long %>%
count(type_col, categories,Place) %>%
left_join(data_long %>% count(type_col, Place, name = "m"),by = c("type_col", "Place")) %>%
mutate(Prop = n/m) %>%
ggplot(aes(x = categories, y = Prop, fill = Place)) +
geom_col(position = position_dodge()) +
geom_text(aes(label = scales::percent(Prop)),
            hjust = 0.1, 
            position = position_dodge(1)) +
facet_wrap(~ type_col, scales = "free_x", ncol = 3) +
scale_fill_brewer(palette = "Oranges") + #scale_x_discrete(limits = positions)+
scale_y_continuous(limits = c(0, 1), labels = scales::percent) +
xlab("") +
ylab("") +
coord_flip() +
theme(panel.background = element_rect(fill = "white"),
        legend.position = "bottom",
        strip.text.x = element_text(size = 15, colour = "black"),
        plot.title = element_text(size = 20, face = "bold"),
        axis.text = element_text(size = 12),
        axis.title = element_text(size = 12))

查看下面正确的输出。然而,我不想显示是和否,而只是显示是的比例。有没有一种简单的方法可以在只保留一个方面的情况下绘制下面的输出(在这种情况下是)?感谢帮助

也许是这样:

library(tidyverse)
#Code
data_long %>%
  count(type_col, categories,Place) %>%
  left_join(data_long %>% count(type_col, Place, name = "m"),by = c("type_col", "Place")) %>%
  mutate(Prop = n/m) %>%
  filter(categories=='Yes') %>%
  mutate(Place=factor(Place,levels = rev(unique(Place)),ordered = T)) %>%
  ggplot(aes(x = categories, y = Prop, fill = Place)) +
  geom_col(position = position_dodge()) +
  geom_text(aes(label = scales::percent(Prop)),
            hjust = 0.1, 
            position = position_dodge(1)) +
  facet_wrap(~ type_col, scales = "free_x", ncol = 3) +
  scale_fill_brewer(palette = "Oranges",guide = guide_legend(reverse = TRUE)) + #scale_x_discrete(limits = positions)+
  scale_y_continuous(limits = c(0, 1), labels = scales::percent) +
  xlab("") +
  ylab("") +
  coord_flip() +
  theme(panel.background = element_rect(fill = "white"),
        legend.position = "bottom",
        strip.text.x = element_text(size = 15, colour = "black"),
        plot.title = element_text(size = 20, face = "bold"),
        axis.text = element_text(size = 12),
        axis.title = element_text(size = 12))

输出: