R语言 将多个图例添加到组合图ggplot2

plicqrtu  于 2023-06-27  发布在  其他
关注(0)|答案(1)|浏览(104)

我有这样的数据:

head(data,10)
   Ratio Wealthness Cash Quality Variants
1      A          A    E       G        r
2      D          B    A       C        u
3      C          B    C       E        s
4      A          C    E       A        s
5      D          B    A       D        y
6      C          B    D       D        x
7      B          C    D       D        v
8      D          C    C       D        y
9      B          C    B       A        x
10     A          A    D       G        u

并根据Rui Barradas为我之前的问题提供的解决方案创建了一个组合图:

library(ggplot2)
library(tidyr)

color_clrs <- c(
    A = "white",
    B = "black",
    C = "black",
    D = "white",
    E = "black",
    F = "white",
    G = "white"
)

fill_clrs <- c(
    A = "#1f3560",
    B = "#B0C4DE",
    C = "#f2f3f3",
    D = "#ff0000",
    E = "#A9A9A9",
    F = "#B22222",
    G = "#1E90FF"
)

ggplot(data %>% pivot_longer(-Variants), aes(Variants, fill = value)) +
    geom_bar(position = "fill") +
    geom_text(stat = "count", aes(label = after_stat(count), color = value), 
              position = position_fill(vjust = 0.5), show.legend = FALSE) +
    facet_wrap(~name) +
    scale_x_discrete(limit = rev) +
    scale_y_continuous(trans = "reverse") +
    scale_fill_manual(values = fill_clrs) +
    scale_color_manual(values = color_clrs) +
    coord_flip() +
    theme_classic() +
    theme(legend.position = "top",
          axis.ticks.x = element_blank(),
          axis.text.x = element_blank())

输出:

**我的问题是如何使单独的图例与颜色和组(A-E)到每列?**在这个问题中,这不是真实的数据示例,实际上有些组可以是1到1000,在这种情况下甚至很难找到颜色。或者它可以是,只有一次,一些字母出现在变量下的所有变体,所以如果看到该变量可以是什么组,这将更容易理解。

7lrncoxx

7lrncoxx1#

你可以在一个函数中转换你的图(与你写的代码相同,我只是删除了facet_wrappivot_longer部分),用purrr::map2在每个子集中应用它,然后合并patchwork::wrap_plots组合列表中的所有图

library(patchwork)

ind_plot <- function(data, plot_titles)
  data %>% 
  ggplot(aes(Variants, fill = value)) +
  geom_bar(position = "fill") +
  geom_text(stat = "count", aes(label = after_stat(count), color = value), 
            position = position_fill(vjust = 0.5), show.legend = FALSE) +
  scale_x_discrete(limit = rev) +
  scale_y_continuous(trans = "reverse") +
  scale_fill_manual(values = fill_clrs) +
  scale_color_manual(values = color_clrs) +
  coord_flip() +
  theme_classic() +
  theme(legend.position = "top",
        axis.ticks.x = element_blank(),
        axis.text.x = element_blank()) + 
  labs(title = plot_titles)

  data %>% 
  pivot_longer(-Variants) %>% 
  split(.$name) %>% 
  purrr::map2(names(.), ind_plot) %>% 
  patchwork::wrap_plots()

创建于2023-06-19带有reprex v2.0.2

相关问题