Reputation: 3075
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.
Upvotes: 2
Views: 6255
Reputation: 23758
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...
> unique(df[,c('class','choose','colorvector')])
class choose colorvector
1 <NA> FALSE gray
3 S TRUE red
5 T TRUE blue
6 V TRUE orange
7 G TRUE black
Now everything will be in the right order.
Upvotes: 0
Reputation: 173527
Thank you!
Thanks you for asking a question that reminded me of why I started using ggplot2
. Lots of folks around here joke about how much ggplot2
is pushed as the answer to plotting questions, and frankly we do over do it a tad.
But man, I can't remember the last time I had to fuss with a legend like this. Try:
library(ggplot2)
ggplot(data = df,aes(x=x,y=y)) +
geom_text(aes(label = ID,colour = class)) +
scale_colour_brewer(pal = 'Set1')
Obviously, you can set your own color palette, this was just one I liked.
Upvotes: 2