在下面的例子中,我的目标是A和B有相同的调色板,C有不同的调色板,D和E有相同的调色板.

# Number of IDs
n_ids <- 10 

# Generate IDs
ids <- paste0("ID_", 1:n_ids)

# Number of periods per ID
n_periods <- 3

# Generate periods
periods <- rep(c("P1", "P2", "P3"), each = n_ids)

# Number of categories 
n_cats <- 5 

# Generate categories
categories <- rep(LETTERS[1:n_cats], times = n_ids * n_periods)

# Generate values
values <- rnorm(n_ids * n_periods * n_cats, 100, 15)

# Assemble into dataframe
df <- data.frame(ID = ids, 
                 Period = periods,
                 Category = categories,
                 Value = values)

# Plot
p <- ggplot(df, aes(x=Period, y=Value, fill=Period)) +
  geom_boxplot() +
  geom_jitter(width=0.2,alpha=0.4, size=1) +
  facet_wrap(~Category, ncol=6, scales='free') +
  labs(title="Repetitive Behavior Score", x="Group", y="Value")

# Color vector
colors <- c("#1F78B4", "#E69F00", "#33A02C", "#FB9A99")

# Map colors to categories
color_map <- c(
  "A" = "#1F78B4",
  "B" = "#1F78B4",
  
  "C" = "#E69F00",
  
  "D" = "#33A02C",
  "E" = "#33A02C"
)

# Set fill scale
p + 
  scale_fill_manual(values = color_map)

但他们都只是回归灰色.以前有人试过这个吗?我知道scale_fillscale_color可以做到,但我找不到小平面面板的例子.

推荐答案

您可以将填充美学映射到x轴和刻面变量的interaction.缺点是您需要手动指定 colored颜色 .

ggplot(df, aes(Period, Value, fill = interaction(Period, Category))) +
  geom_boxplot() +
  geom_jitter(width = 0.2, alpha = 0.4, size = 1) +
  facet_wrap(~Category, ncol = 6, scales = 'free') +
  labs(title = "Repetitive Behavior Score", x = "Group", y =" Value") +
  scale_fill_manual(values = c(rep(c("red4", "green4", "blue4"), 2),
                               c("hotpink", "orange", "dodgerblue"),
                               rep(c("purple3", "beige", "gray80"), 2)),
                    guide = guide_none()) +
  jtools::theme_apa() 

enter image description here

R相关问答推荐

提取rame中对应r中某个变量的n个最小正值和n个最大负值的条目

使用rlang s arg_match判断函数输入列表

par函数中的缩写,比如mgp,mar,mai是如何被破译的?

如何在ggplot图中找到第二轴的比例

如何在观测缺失的地方添加零

根据元素和前一个值之间的差值过滤矩阵的元素

将小数分隔符放在R中的前两位数字之后

如何在ggplot2中绘制具有特定 colored颜色 的连续色轮

从非重叠(非滚动)周期中的最新数据向后开窗并在周期内计数

如何将使用rhandsontable呈现的表值格式化为百分比,同时保留并显示完整的小数精度?

悬崖三角洲超大型群数计算导致整数溢出

从多面条形图中删除可变部分

在点图上绘制置信度或预测区间ggplot2

按组内中位数分类

为什么在写入CSV文件时Purrr::Pwalk不起作用

Rmarkdown::Render vs Source()

变异以按组从其他列创建具有最大和最小值的新列

注释不会绘制在所有ggplot2面上

如何将字符类对象中的数据转换为R中的字符串

从矩阵创建系数图