色轴标签(按组) [英] Color axis labels by group

查看:56
本文介绍了色轴标签(按组)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要给x轴标签加上与框相同的颜色.例如,

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

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

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

但是我有一个更大的数据集,这使得手动着色变得更加困难.最好使用 colour = grp 类型的命令.谢谢!

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

推荐答案

也许有更好的方法,但是由于ggplot的 scale_fill_discrete 调用 scales :: hue_pal ,您可以使用它生成与绘图相同的颜色:

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)

此处的 x_cols 定义使用 hue_pal 创建调色板 function ,然后调用该函数以生成调色板,只要组.只要子组(A1,A2等)的长度相等,就可以使用 rep .也许有人可以将其扩展到更一般的情况.

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.

这篇关于色轴标签(按组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆