问题
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])
Thank you for any help!
回答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])
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
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.
来源:https://stackoverflow.com/questions/19874240/how-to-assign-specfic-colours-to-specifc-categorical-variables-in-r