I am having problems matching the correct color vector which I use in ‘plot’ function and the color vector in a subset of my data which I use to add a legend to my data. I was windering if you have any suggestions? I have been trying to specify an order for the colorvector, but when I turn it into factor the levels of the factors are re-ordered automatically.
This is my sample data:
ID<- c(1,2,3,4,5,6,7,8)
class<- c(NA,NA,'S','S','T','V','G','S')
x<- c(5,3,2,7,6,4,8,3)
y<- c(8,4,1,8,4,8,3,1)
df<- data.frame(ID,class,x,y)
df$choose <- c('FALSE', 'FALSE', 'TRUE', 'TRUE','TRUE','TRUE', 'TRUE', 'TRUE')
df$colorvector <- 'gray'
split(df$colorvector, df$class)<- c('black', 'red', 'blue', 'orange')
plot(df$x,df$y,col=df$colorvector)
text(df$x[df$choose==TRUE], df$y[df$choose==TRUE], labels=df$ID[df$choose==TRUE], cex=0.8, pos=2, font=1)
legend("topright", inset=.05, title="IDs with same class",
legend=sort(levels(df$class[df$choose==TRUE])), fill=levels(as.factor(df$colorvector[df$choose==TRUE])), horiz=TRUE)
Thank you in advance for your help.
You’re making the mistake of assuming that when you make colorvector into a factor that its levels sort in the same was as class. One solution would be to just assign your colours in alphabetical order. A better way might be to get your legend information from this data…
Now everything will be in the right order.