繁体   English   中英

ggplot不重新调整scale_fill_manual()中的颜色顺序?

[英]ggplot not respectig order of colours in scale_fill_manual()?

我正在创作一些小提琴情节,并希望给它们上色。 它适用于维度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

这里它不起作用(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

这与设定因子水平有关 由于variable_grouping是一个字符, ggplot2会将其转换为绘图因子。 它使用默认因子顺序,其中1始终位于2之前。 所以在你的例子11-15中所有人都来自传奇中的2。

您可以手动设置因子顺序以避免默认顺序。 forcats::fct_inorder()使用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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM