如何使用 table 布尔类别作为 x 轴标签在 R 中制作条形图?

How do I make a barplot in R with a table of boolean categories as the x axis label?

我有一个按 5 个属性分类的案例计数数据框,每个属性为 TRUE、FALSE 或 NA。我试图找到一种方法来将不同属性组合的计数呈现为 R 中的图。 下面是一些数据(真实数据多了几个属性):

> df <- data.frame( attibute_A = c(T,F,T,NA,F), attribute_B = c(F,T,T,NA,T), attribute_C = c(T,T,F,F,F), attribute_D = c(T,T,NA,NA,F), count=c(100,55,34,12,3))
> df
  attibute_A attribute_B attribute_C attribute_D count
1       TRUE       FALSE        TRUE        TRUE   100
2      FALSE        TRUE        TRUE        TRUE    55
3       TRUE        TRUE       FALSE          NA    34
4         NA          NA       FALSE          NA    12
5      FALSE        TRUE       FALSE       FALSE     3

这是一个条形图的模型,我认为我可以制作它来展示具有不同属性组合的案例数:

我可能没有使用正确的关键字进行搜索,但我无法完全找到我想要制作的情节类型的任何示例,所以我不确定该怎么做。我是否需要将热图与条形图相结合,或者是否有更好的方法来实现这一点?像这样的情节实际上叫什么(如果有名字的话)?

不完全是您想要的,但可能是一个开始。 编辑:肮脏的 hack 在空栏中设置 colnames

library(tidyverse)

df %>% 
  rbind(c(names(df)[1:4],0)) %>%
  unite("label", starts_with("att"), sep = "\n") %>%
  mutate(count = as.numeric(count)) %>%
  ggplot(aes(x = label, y = count)) +
  geom_col() +
  labs(x = "")

如果你想在一个 ggplot 调用中完成所有操作,而不将绘图拼接在一起,你可以这样做:

library(tidyverse)

ystep <- max(df$count, na.rm = TRUE) / 5

df %>% mutate(A = paste(attribute_A), B = paste(attribute_B),
              C = paste(attribute_C), D = paste(attribute_D)) %>%
  ggplot(aes(x = 1:5, y = count)) +
  geom_col(fill = 'deepskyblue3', color = 'deepskyblue4', width = 0.5) +
  scale_y_continuous(limits = c(-max(df$count), max(df$count)),
                     breaks = c(4:1 * -ystep, pretty(df$count)),
                     labels = c(names(df[4:1]),  pretty(df$count))) +
  geom_tile(aes(y = -1 * ystep, fill = A, color = A), height = ystep) +
  geom_tile(aes(y = -2 * ystep, fill = B, color = B), height = ystep) +
  geom_tile(aes(y = -3 * ystep, fill = C, color = C), height = ystep) + 
  geom_tile(aes(y = -4 * ystep, fill = D, color = D), height = ystep) +
  geom_text(aes(y = -1 * ystep, label = A, color = A), fontface = 2) +
  geom_text(aes(y = -2 * ystep, label = B, color = B), fontface = 2) +
  geom_text(aes(y = -3 * ystep, label = C, color = C), fontface = 2) +
  geom_text(aes(y = -4 * ystep, label = D, color = D), fontface = 2) +
  scale_fill_manual(values = c('pink', 'gold2', 'lightgreen')) +
  scale_color_manual(values = c('red4', 'orange4', 'green4')) +
  theme_minimal() +
  theme(panel.grid.major.x = element_blank(),
        panel.grid.minor.x = element_blank(),
        axis.text.x = element_blank(),
        axis.title.x = element_blank(),
        axis.title.y = element_text(hjust = 0.75),
        legend.position = 'none')