2013-05-29 114 views
0

我需要将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)) 

enter image description here

在上面的图像,我想在颜色红色,B1/B2的A1/A2的x轴标签在蓝绿色和C1/C2。以下可能的工作,

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

enter image description here

但我有一个更大的数据集这使得它更难手动颜色。更喜欢colour=grp类型的命令。谢谢!

回答

1

有可能是一个更好的方式来做到这一点,但由于ggplot的scale_fill_discrete电话scales::hue_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) 

x_cols定义在这里创建了一个调色板功能hue_pal,然后调用该函数生成一个调色板,只要组数。只要子组(A1,A2等)的长度相等,使用rep就可以工作。也许有人可以扩展这个更普遍的情况。

+0

谢谢!我推广如下:'x_cols = hue_pal()(length(levels(df $ grp))); names(x_cols)= levels(df $ grp); myplot + theme(axis.text.x = element_text(color = x_cols [substr(levels(df $ Var1),1,1)]))' – harkmug

+1

请注意'scale_fill/color_discrete'采用'hue_pal'的相同参数,所以你可以制作一个通用的自定义调色板。 –