[英]Programmatically specifying colours in scale_fill_manual ggplot call
[英]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
這與設定因子水平有關 。 由於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.