R 按组显示颜色轴标签

R 按组显示颜色轴标签,r,ggplot2,themes,R,Ggplot2,Themes,我需要将x轴标签的颜色与框的颜色相同。比如说, library(ggplot2) library(reshape2) df = matrix(rnorm(60),6,10) rownames(df) = paste0(rep(c("A","B","C"),2),1:2) df=melt(df) df = cbind(df,grp=substr(df$Var1,1,1)) ggplot(df) + geom_boxplot(aes(x=Var1, y=value, fill=grp)) 在上图

我需要将x轴标签的颜色与框的颜色相同。比如说,

library(ggplot2)
library(reshape2)
df = matrix(rnorm(60),6,10)
rownames(df) = paste0(rep(c("A","B","C"),2),1:2)
df=melt(df)
df = cbind(df,grp=substr(df$Var1,1,1))
ggplot(df) + geom_boxplot(aes(x=Var1, y=value, fill=grp))

在上图中,我想将A1/A2的x轴标签涂成红色,B1/B2涂成绿色,C1/C2涂成蓝色。以下方法可能有效

theme(axis.text.x = element_text(colour=c(rep("red",2), rep("green",2), rep("blue",2))))


但是我有一个大得多的数据集,这使得手工着色变得更加困难。希望使用
color=grp
type命令。谢谢

可能有更好的方法来实现这一点,但由于ggplot的
scale\u fill\u discrete
调用
scales::hue\u pal
,因此您可以使用它生成与绘图相同的颜色:

library(ggplot2)
library(reshape2)
df = matrix(rnorm(60),6,10)
rownames(df) = paste0(rep(c("A","B","C"),2),1:2)
df=melt(df)
df = cbind(df,grp=substr(df$Var1,1,1))
myplot <- ggplot(df) + geom_boxplot(aes(x=Var1, y=value, fill=grp))

library(scales)
x_cols <- rep(hue_pal()(length(unique(df$grp))), each=2)
myplot <- myplot + theme(axis.text.x = element_text(colour=x_cols)
库(ggplot2)
图书馆(E2)
df=矩阵(rnorm(60),6,10)
行名(df)=粘贴0(代表(c(“A”、“B”、“c”),2),1:2)
df=熔体(df)
df=cbind(df,grp=substr(df$Var1,1,1))

我的阴谋谢谢!我概括如下:
x_cols=hue_pal()(长度(levels)(df$grp));名称(x_cols)=级别(df$grp);myplot+theme(axis.text.x=element\u text(color=x\u cols[substr(levels(df$Var1),1,1)])
注意,
scale\u fill/color\u discrete
采用与
hue\u pal
相同的参数,因此您可以制作一个通用的定制调色板。