重新排列 ggplot 中的条形

问题描述 投票:0回答:1

我想重新排列下图中的条形。我想并排显示 CT 和 HS 条形图,例如首先显示 1DAS CT 和 HS 条形图,然后显示 15DAS CT 和 HS 条形图,依此类推。我正在使用以下代码

ggplot(data, aes(x = Genotype, y = Pn, fill = DAS)) +
  geom_col_pattern(aes(pattern = Treatment), pattern_color = '#00000050',
                   position = position_dodge(0.7), width = 0.5, 
                   color = 'gray50',
                   pattern_angle = 45, pattern_spacing = 0.02) +
  scale_pattern_manual(values = c('none', 'stripe'),
                       guide = guide_legend(override.aes = list(fill = 'white'))
  ) +
  scale_fill_brewer('Species', palette = 'Pastel2', 
                    guide = guide_legend(override.aes = list(pattern = 'none'))
  ) + 
  theme_minimal(base_size = 16) +
  theme(axis.text.x.bottom = element_text(face = "bold"),
        panel.spacing.x = unit(0, 'mm'),
        panel.grid.major.x = element_blank(),
        axis.text.x = element_text(angle=90))

我得到了这张图表,其中对于每个基因型,它首先显示 CT 条形图,然后显示 HS 条形图。 enter image description here

r ggplot2 bar-chart
1个回答
0
投票

最终可以通过设置适当的群体审美来控制排序。

这里我制作了一些与您类似的数据,然后进行一些因式分解来控制排序顺序。排序后,我计算一个

grp_ord
列,指示所需的顺序,并将其传递给
aes(group = grp_ord)
美学。

library(dplyr)
library(forcats)
library(ggplot2)
library(ggpattern)

# data similar to yours
data <- expand.grid(
  genotype = c("BGB001", "BGB011"),
  das = c("1DAS", "15DAS", "35DAS"),
  treatment = c("CT", "HS")
) %>%
  mutate(pn = runif(12, 0, 15))

data %>%
  # set factor levels to control ordering
  mutate(
    genotype = factor(genotype, levels = c("BGB001", "BGB011")),
    das = factor(das, levels = c("1DAS", "15DAS", "35DAS")),
    treatment = factor(treatment, levels = c("CT", "HS"))
  ) %>%
  # order as desired
  arrange(genotype, das, treatment) %>%
  # compute group factor with desired order
  mutate(grp_ord = interaction(genotype, das, treatment),
         grp_ord = fct_inorder(grp_ord)) %>%
  ggplot(aes(
    x = genotype,
    y = pn,
    fill = das,
    group = grp_ord
  )) +
  geom_col_pattern(
    aes(pattern = treatment),
    pattern_color = '#00000050',
    position = position_dodge(0.7),
    width = 0.5,
    color = 'gray50',
    pattern_angle = 45,
    pattern_spacing = 0.02
  )

创建于 2024-05-21,使用 reprex v2.1.0

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.