1
votes

I use gather function reform the format of data
Then use separate function to split the "Petal.Width: into Petal(part variable) and Width(measurement variable). Then I want to picture a scatter plots based on Petal and Sepal. But after I convert the part variable into factor, I cannot use two kinds colors base the parts.

     col=c('red','blue')[iris2$Part],
     xlab = 'Length',ylab='Width',
     xlim=c(1,10),ylim=c(0,5),type = 'p')

i USE col=c('red','blue')[iris2$part], but it only use the blue or the second color whichever I chosen.

iris2<-gather(iris,'Part','Number',-Species)
iris2<-separate(iris2,col='Part',into=c('Part','Measure'))
#iris2<-iris2[rank(iris2$Part)]
iris2$Part<-as.factor(iris2$Part)
plot(iris2$Number[iris2$Measure=='Length'],iris2$Number[iris2$Measure=='Width'],
     col=c('red','blue')[iris2$Part],
     xlab = 'Length',ylab='Width',
     xlim=c(1,10),ylim=c(0,5),type = 'p')

I think it may be caused by the sequence of the factor, the sepal list 2 and petal list as 1. but it comes 2 first in iris2 dataset, so it always choose second color. just my guess.

'data.frame':   600 obs. of  4 variables:
 $ Species: Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ Part   : Factor w/ 2 levels "Petal","Sepal": 2 2 2 2 2 2 2 2 2 2 ...
 $ Measure: chr  "Length" "Length" "Length" "Length" ...
 $ Number : num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
1

1 Answers

0
votes

The problem is your filtering in your plot definition. iris2$Number[iris2$Measure=='Length'] and iris2$Number[iris2$Measure=='Width'] are both vectors of 300 elements but iris2$Part is a vector of 600 elements therefore only the first 300 elements are being used. In this case all of the "Petal" factors which has a value of 2.
If you substitute in iris2$Part[iris2$Measure=='Length'] this should provide something closer to what you were expecting.

plot(iris2$Number[iris2$Measure=='Length'],iris2$Number[iris2$Measure=='Width'],
     col=c('red','blue')[iris2$Part[iris2$Measure=='Length']],
     xlab = 'Length',ylab='Width',
     xlim=c(1,10),ylim=c(0,5),type = 'p')

enter image description here