如何使用 ggplot 和 facet_wrap 在 R 中绘制因子属性

How do I use ggplot and facet_wrap for plotting factor attributes in R

我有一个数据集,其中包含许多共享共同值(价格范围,例如“£11-£20”、“£21-£30”...)的属性,这些属性存储为因子。我正在尝试使用 facet_wrap 绘制这些属性的选择,并在 x 轴上绘制每个属性的计数条形图和价格范围。

我可以单独获得我想要的图表,但我想将这些属性分组,因为它们是相关的。示例代码如下:

dat <- data.frame(
  breakfast = factor(c("£11-£20","£11-£20","£21-30","£0-£10","£11-£20")),
  lunch = factor(c("£0-£10","£11-£20","£21-30","£11-£20","£21-30")),
  dinner = factor(c("£0-£10","£31-£40","£21-30","£11-£20","£21-30")),
  voucher_used = c(0,1,1,0,1)
)
View(dat)

ggplot(dat, aes(x = breakfast, fill = factor(voucher_used))) +
  geom_bar() +
  xlab("Breakfast") +
  ylab("No.") +
  labs(fill = "Voucher Used") # +
# facet_wrap(~ lunch)

理想情况下,我想为午餐和晚餐添加相同的地块 - 是否有可能或是否有其他更好的方法来实现相同的结果?

非常感谢

是的,可以使用一些 tidyverse 函数将您的数据重塑为长格式:

library(ggplot2)
library(dplyr)
library(tidyr)
#Data
dat <- data.frame(
  breakfast = factor(c("£11-£20","£11-£20","£21-30","£0-£10","£11-£20")),
  lunch = factor(c("£0-£10","£11-£20","£21-30","£11-£20","£21-30")),
  dinner = factor(c("£0-£10","£31-£40","£21-30","£11-£20","£21-30")),
  voucher_used = c(0,1,1,0,1)
)
#Plot
dat %>% pivot_longer(-voucher_used) %>%
  ggplot(aes(x = value, fill = factor(voucher_used))) +
  geom_bar() +
  xlab("Breakfast") +
  ylab("No.") +
  labs(fill = "Voucher Used") +
  facet_wrap(~ name,scales = 'free')+xlab('Var')

输出: