【问题标题】:ggplot not respectig order of colours in scale_fill_manual()?ggplot不尊重scale_fill_manual()中的颜色顺序?
【发布时间】:2018-11-11 19:32:10
【问题描述】:

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

ggplot violin plot, specify different colours by group?

但是当我将维度增加到 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 变量被 ggplot 转换为因子,因此使用默认级别顺序(其中 1 位于 2 之前)。如果您想控制因子水平的顺序,您需要自己“手动”设置水平。我为此使用forcats::fct_inorder(),因为它很方便,比如fill = forcats::fct_inorder(variable_grouping)
  • @aosmith 这行得通。如果您将其发布为答案,我将接受它。

标签: r ggplot2 violin-plot


【解决方案1】:

这与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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-06
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 2017-12-22
    相关资源
    最近更新 更多