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.
Best Answer
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 muchggplot2
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:
Obviously, you can set your own color palette, this was just one I liked.