我正在创作一些小提琴的情节,并想给它们着色。它适用于维数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
发布于 2018-06-01 08:32:30
这与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)
发布于 2022-02-11 06:52:19
您也可以命名颜色向量。例如:
my_values <- rep(c("red","green","blue"),5)
names(my_values) <- rep(c("Data1","Data2","Data3"),5)
... +
scale_fill_manual(values=my_values)
https://stackoverflow.com/questions/50647122
复制相似问题