首页 > 解决方案 > 如何使用 ggplot 在 R 中创建不均匀的 facet_wrap 网格?

问题描述

我目前正在使用 R 中的 ggplot2 绘制一个图表,我想在其中使用 facet_wrap 创建 5 个子图。

到目前为止,这是我的代码:

# getting the data
data = structure(list(type = c("red", "blue", "orange", "yellow", "green", 
       "red", "blue", "orange", "yellow", "green", "red", "blue", "orange", 
       "yellow", "green", "red", "blue", "orange", "yellow", "green"), 
       cond = c("new", "new", "new", "new", "new", "old", "old", 
       "old", "old", "old", "new", "new", "new", "new", "new", "old", 
       "old", "old", "old", "old"), fact = c("light", "light", "light", 
       "light", "light", "light", "light", "light", "light", "light", 
       "shiny", "shiny", "shiny", "shiny", "shiny", "shiny", "shiny", 
       "shiny", "shiny", "shiny"), score = c(2L, 4L, 8L, 6L, 10L, 3L, 
       5L, 9L, 1L, 3L, 12L, 14L, 18L, 16L, 20L, 13L, 15L, 19L, 11L, 
       13L)), class = "data.frame", row.names = c(NA, -20L))

library(ggplot2)

ggplot(data=data, aes(x=cond, y=score, fill=fact)) +
  geom_bar(stat="identity", position=position_dodge()) +
  theme_bw() + facet_wrap(. ~ type, ncol=3) 

这将创建以下图:

现在的样子

但是,由于其中一种颜色比其他颜色重要得多,我想创建以下选项之一:

所需选项

有谁知道如何让 facet_wrap 做到这一点,或者可以指出另一个选项来创建它?

干杯,马克斯

标签: rggplot2visualizationfacet-wrap

解决方案


这是混合patchwork和方面的方法。

blue为其他所有内容创建一个情节。从蓝色图中删除图例,并从另一个图中删除 y 轴标题。

library(tidyverse)
library(patchwork)

p_other <-
  data %>%
  filter(type != "blue") %>%
  ggplot(aes(x = cond, y = score, fill = fact)) +
    geom_bar(stat = "identity", position = position_dodge()) +
    theme_bw() +
    facet_wrap(. ~ type, ncol = 2) +
    theme(axis.title.y = element_blank())

p_blue <-
  data %>%
  filter(type == "blue") %>%
  ggplot(aes(x = cond, y = score, fill = fact)) +
    geom_bar(stat = "identity", position = position_dodge()) +
    theme_bw() +
    facet_wrap(. ~ type, ncol = 2) +
    theme(legend.position = "none")

|使用from patchwork添加一列。

(p_blue | p_other) + plot_layout(widths = c(1, 2))

阴谋


推荐阅读