根据另一个变量改变 R 中轴标签的颜色 [英] Vary colors of axis labels in R based on another variable

查看:15
本文介绍了根据另一个变量改变 R 中轴标签的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常使用 ggplot2,但在这种情况下,我使用常规的 image() 函数来绘制大型数据集的热图.我可以将所有标签标记为红色,但我想根据我生成的颜色定义向量用不同颜色的文本标记 y 轴:

I usually use ggplot2, but in this case I am using the regular image() function to plot a heatmap of a large data set. I can label all the labels as red, but I want to label the y-axis with text of different colors based on a vector of color definitions that I generate:

grid = structure(c(1:12),.Dim = c(4,3))
labs = c("A","B","C")
image(1:4,1:3,grid,axes=FALSE, xlab="", ylab = "")
#This works but isn't the colors I want
axis(2,at=1:length(labs),labels=labs,las=2, adj=1,cex.axis=0.6,col.axis="red")

生成以下图像:

我希望标签 A 和 C 为黑色,B 为红色.这是我尝试过的,但它给出了错误的长度"错误...

I would like labels A and C to be black and B to be red. This is what I tried, but it gives a "wrong length" error...

axiscolors = c("black","red","black")
axis(2,at=1:length(labs),labels=labs,las=2, adj=1, cex.axis=0.6, col.axis=axiscolors)

这是我使用一些真实"数据后得到的效果...

This is the effect I am after with some "real" data...

作为备份,如果这在 ggplot2 中是可能的,我可能愿意重构我的代码.还有一些其他应用程序我也会使用它.

As a back-up, if this is possible in ggplot2, I might be willing to re-factor my code. There are a couple other applications I would use this for as well.

我想出了一种在旧标签顶部绘制一层红色符号的方法,但如果可能的话,我更喜欢带有颜色矢量的本机方法......

I figured out a way to plot a layer of red symbols over the top of the old labels, but would prefer a native method with the color vector, if possible...

sublabs = c("B")
axis(2,at=match(sublabs,labs),labels=sublabs,las=2, adj=1, cex.axis=0.6, col.axis="red")

如果我可以将标签放在绘图空间之外,另一种方法是使用 text()...

Another way would be to use text() if I could put the labels outside the plot space...

text(c(1,1,1),c(1,2,3),labs,col=c("black","red","black"))

更新:请参阅下文,了解适用于 ggplot2...

UPDATE: See below for a solution that works with ggplot2...

推荐答案

如果你忽略了像 textmtext 这样的矢量化可能性,你可以通过重复调用 <代码>轴.时间上的开销将非常小,它将允许所有 axis 计算正常进行.例如:

If you ignore the vectorised possibilities like text and mtext, you can get there by repeatedly calling axis. The overhead timewise will be very minimal and it will allow all the axis calculations to occur as they normally do. E.g.:

# original code
grid = structure(c(1:12),.Dim = c(4,3))
labs = c("A","B","C")
image(1:4,1:3,grid,axes=FALSE, xlab="", ylab = "")
axiscolors = c("black","red","black")

# new code    
Map(axis, side=2, at=1:3, col.axis=axiscolors, labels=labs, lwd=0, las=1)
axis(2,at=1:3,labels=FALSE)

导致:

这篇关于根据另一个变量改变 R 中轴标签的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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