如何将特定颜色分配给 R 中的特定分类变量? [英] How to assign specfic colours to specifc categorical variables in R?

查看:85
本文介绍了如何将特定颜色分配给 R 中的特定分类变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 R 的完全初学者并且有这个问题.我使用以下代码生成颜色列表,然后创建大量散点图矩阵.我想为矩阵的第一列分配特定的颜色(4 个类别的分类).运行此代码工作正常,但如何验证我打算为每个分类变量指定的颜色是否正确?

I'm a complete beginner to R and have this question. I'm using the following code to generate a colour list and then create a massive scatterplot matrix. I want to assign specific colours to the first column of my matrix(categorical with 4 categories). Running this code works fine but how do I verify that the colours that I intend to specify for each of the categorical variables is correct?

基本上我想实现控制"的绿色,低"的橙色,中"的棕色和高"的黑色.

Basically I want to achieve green for 'control', orange for 'low', brown for 'medium' and black for 'high'.

col.list<-c("green","orange","brown","black")

palette(col.list)

pairs(Indices[,4:17], col=Indices[,1])

感谢您的帮助!

推荐答案

你的做法是正确的.如果您想检查颜色是否确实与您的组相对应,您可以这样做,例如(这里有一个可重复的示例):

The way you're doing it is correct. If you want to check that indeed the colours correspond to your group, you can, for example do it that way (here with a reproducible example):

set.seed(1)
a <- data.frame(Group=factor(sample(c("control","low","medium","high"),20,TRUE),
                             levels= c("control","low","medium","high")),
                x=rnorm(20),y=rnorm(20))
col.list <- c("green","orange","brown","black")
palette(col.list)
pairs(a[,2:3], col=a[,1])

col=a[,1] 实际上是 palette()[a[,1]](如果列的内容是一个因素,它就起作用或整数),让我们看看:

What col=a[,1] does is actually palette()[a[,1]] (which works IF the content of the column is a factor or an integer), so let's see:

palette()[a[,1]]
[1] "orange" "orange" "brown"  "black"  "green"  "black"  "black"  "brown"  "brown"  "green"  "green"  "green"  "brown"  "orange"
[15] "black"  "orange" "brown"  "black"  "orange" "black" 

table(a[,1], palette()[a[,1]])
         black brown green orange
  control     0     0     4      0
  low         0     0     0      5
  medium      0     5     0      0
  high        6     0     0      0

你唯一真正需要担心的是,Indices[,1] 的内容是一个因子,其级别与相应颜色列表的顺序相同.

The only thing you really have to worry about is that the content of Indices[,1] is a factor whose levels are ordered in the same order as the corresponding color list.

这篇关于如何将特定颜色分配给 R 中的特定分类变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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