2013-05-29 3 views
0

x 축 레이블의 색을 상자와 동일하게 지정해야합니다. 예를 들어, 상기 이미지에서 그룹 별 색 축 레이블

enter image description here

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

, I는 청색, 녹색, C1/C2로 빨강, B1/B2의 A1/A2의 X 축 라벨 색상 싶다. 다음은 작동 할 수 있습니다,

enter image description here

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

하지만 어렵게 수동으로 색상을 만드는 훨씬 더 큰 데이터 세트 있습니다. 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으로 변경 한 다음 그룹 수만큼 팔레트를 생성하기 위해 해당 함수를 호출합니다. rep을 사용하면 하위 그룹 (A1, A2 등)의 수가 동일한 길이이면 작동합니다. 어쩌면 누군가가 좀 더 일반적인 경우에 이것을 확장 할 수 있습니다.

+0

감사합니다. 나는 다음과 같이 일반화했다 :'x_cols = hue_pal() (length (levels (df $ grp))); 이름 (x_cols) = 수준 (df $ grp); ' – harkmug

+1

'scale_fill/color_discrete'는'hue_pal'과 같은 인자를가집니다. myplot + theme (axis.text.x = element_text (color = x_cols [substr (levels (df $ Var1), 1,1)]) , 사용자 정의 팔레트를 만들 수 있습니다. –