ggplot 不尊重 scale_fill_manual() 中的颜色顺序?

ggplot not respectig order of colours in scale_fill_manual()?

我正在创建一些小提琴图并想给它们上色。它适用于维度 9 的矩阵,如我之前的问题

但是当我将维度增加到 15 时,颜色的顺序没有得到遵守。为什么会这样?

这里有效(9 列):

library(ggplot2)
dat <- matrix(rnorm(250*9),ncol=9)

# Violin plots for columns
mat <- reshape2::melt(data.frame(dat), id.vars = NULL)

mat$variable_grouping <- as.character(sort(rep(1:9,250)))



pp <- ggplot(mat, aes(x = variable, y = value, fill = variable_grouping)) + 
  geom_violin(scale="width",adjust = 1,width = 0.5)  + scale_fill_manual(values=rep(c("red","green","blue"),3))
pp

这里不行(15列):

library(ggplot2)
dat <- matrix(rnorm(250*15),ncol=15)

# Violin plots for columns
mat <- reshape2::melt(data.frame(dat), id.vars = NULL)

mat$variable_grouping <- as.character(sort(rep(1:15,250)))



pp <- ggplot(mat, aes(x = variable, y = value, fill = variable_grouping)) + 
  geom_violin(scale="width",adjust = 1,width = 0.5)  + scale_fill_manual(values=rep(c("red","green","blue"),5))
pp

这与 setting factor levels 有关。由于 variable_grouping 是一个字符,因此 ggplot2 将其转换为绘图的因子。它使用默认的因子顺序,其中 1 总是在 2 之前。所以在你的例子中,11-15 都出现在图例中的 2 之前。

您可以手动设置因子顺序以避免默认顺序。我为此使用 forcats::fct_inorder() 是因为在您希望因子的顺序与变量的顺序相匹配的情况下它很方便。请注意,您也可以直接使用 factor() 并通过 levels 参数设置级别顺序。

ggplot(mat, aes(x = variable, y = value, fill = forcats::fct_inorder(variable_grouping))) + 
     geom_violin(scale="width", adjust = 1, width = 0.5)  + 
     scale_fill_manual(values=rep(c("red","green","blue"),5)

您也可以命名颜色矢量。例如:

my_values <- rep(c("red","green","blue"),5)
names(my_values) <- rep(c("Data1","Data2","Data3"),5)


... +
  scale_fill_manual(values=my_values)