问题
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