Color axis labels by group

可紊 提交于 2019-12-12 05:04:42

问题


I need to color the x-axis labels the same as the boxes. For example,

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

In the image above, I would like to color the x-axis labels of A1/A2 in red, B1/B2 in green and C1/C2 in blue. The following might work,

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

But I have a much larger dataset which makes it harder to color manually. Would prefer a colour=grp type command. Thanks!


回答1:


There might be a better way to do this, but since ggplot's scale_fill_discrete calls scales::hue_pal, you can use this to generate the same colors that your plot uses:

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)

The x_cols definition here creates a palette function with hue_pal, and then calls that function to generate a palette as long as the number of groups. Using rep will work as long as the number of subgroups (A1, A2, etc.) are of equal length. Maybe someone can extend this for a more general case.



来源:https://stackoverflow.com/questions/16823630/color-axis-labels-by-group

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!