set.seed(3)
values <- rnorm(36)
library(ggplot2)
library(ggpattern)
mydat <- data.frame(time = factor(c(rep(0, 12), rep(1, 12), rep(2, 12))),
                    class = factor(rep(c(rep("A", 6), rep("B", 6)), 3)),
                    method = factor(rep(c(rep("Manual", 3), rep("Automatic", 3)), 6)),
                    value = values)
> head(mydat)
  time class    method       value
1    0     A    Manual -0.96193342
2    0     A    Manual -0.29252572
3    0     A    Manual  0.25878822
4    0     A Automatic -1.15213189
5    0     A Automatic  0.19578283
6    0     A Automatic  0.03012394

我有一个包含4个类别的数据集:2个类x 2个方法.我想在每个时间点用不同的 colored颜色 和图案做一个并排的盒子图.

> ggplot(mydat, aes(x = time, y = value, fill = method, pattern = class)) +
  geom_boxplot_pattern(position = position_dodge(width = 0.8), aes(pattern = class, pattern_fill = class), pattern_density = 0.35) +
  geom_boxplot(position = position_dodge(width = 0.8))

这为我提供了以下图案未正确对齐的情况:

enter image description here

我希望它看起来像这样:

enter image description here

推荐答案

你只需要一层.您可以通过scale_pattern_manual将其中一个图案指定为"无",将另一个图案指定为"条纹"

ggplot(mydat, aes(x = time, y = value, fill = method, pattern = class)) +
  geom_boxplot_pattern(position = position_dodge(width = 0.8),
                       aes(pattern = class), pattern_fill = "black",
                       pattern_density = 0.05, pattern_angle = 45,
                       pattern_spacing = 0.03, width = 0.6) +
  scale_pattern_manual(values = c("none", "stripe")) +
  guides(fill = guide_legend(override.aes = list(pattern = 'none'))) +
  scale_fill_manual(values = c("#fddaf0", "#dfffda")) +
  theme_classic(base_size = 16) 

enter image description here

R相关问答推荐

在ComplexHeatmap中,如何更改anno_barplot()标题的Angular ?

如何从其他前面列中减go 特定列的平均值?

r—绘制相交曲线

在使用ggroove后,将图例合并在gplot中

用预测NLS处理R中生物学假设之上的误差传播

用相同方法得到不同函数的ROC最优截断值

我不能在docker中加载sf

未识别时区

为什么当用osmdata映射R时会得到相邻状态?

使用across,starts_with和ifelse语句变更多个变量

根据文本字符串中的值粘贴新列

如何同时从多个列表中获取名字?

通过在colname中查找其相应值来创建列

R中的哈密顿滤波

如何将Which()函数用于管道%>;%

R -如何分配夜间GPS数据(即跨越午夜的数据)相同的开始日期?

删除在R中的write.table()函数期间创建的附加行

将数据从一列转换为按组累计计数的单个虚拟变量

根据排名的顶点属性调整曲线图布局(&Q)

在R中添加要打印的垂直线