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

Sno*_*ogg 1 r ggplot2 violin-plot

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

ggplot小提琴图,按组指定不同的颜色?

但是当我将维度增加到 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
Run Code Online (Sandbox Code Playgroud)

这里不起作用(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
Run Code Online (Sandbox Code Playgroud)

aos*_*ith 5

这与设定因子水平有关。由于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)
Run Code Online (Sandbox Code Playgroud)