R plotCI incorrectly assigned colors plotted for a series

In R v2.14.0 x64 on Windows 7, I use the plotCI function in the gplots library and try to set the color of each graph based on the data in the data frame using:

plotCI( x = data[1:2,3], ui = data[1:2,5], li = data[1:2,4], col=data[1:2,6], lty = 1, pch=20, xaxt ="n", xlim = c(1,42), ylim = c(0,100), gap = 0 ) 

The graph is displayed correctly, except for the color of the plotted points, which are incorrectly assigned to the wrong row (however, the colors within the row coincide).

I have a structure data structure (only the first 7 lines):

  size qim X1 lower upper color 1 1000 1 100.0000 99.6000 100.0000 blue 2 1000 2 99.8000 99.4000 100.0000 blue 3 1000 3 98.2000 96.6000 99.2000 blue 4 1000 4 62.7000 58.8000 65.7000 blue 5 1000 5 10.4000 9.0000 12.5000 blue 6 1000 6 3.9000 2.9000 4.9000 blue 7 5000 1 99.9000 99.4000 100.0000 red 

I am sorting a data frame using:

 data <- data.unsorted[with(data,order(qim,size)),] 

It seems that sorting happened correctly with the resulting data frame:

  size qim X1 lower upper color 1 1000 1 100.0000 99.6000 100.0000 blue 7 5000 1 99.9000 99.4000 100.0000 red 13 10000 1 99.7000 99.4000 99.9000 green 19 40909 1 98.5000 98.5000 98.5000 black 25 152228 1 98.1000 98.1000 98.1000 black 31 241707 1 98.9000 98.9000 98.9000 black 37 434844 1 97.4000 97.4000 97.4000 black 

In the resulting graph, the first line is displayed in red, and the second - in blue (inverted).

Is there something I'm doing wrong, or is there some other explanation for this?

+4
source share
1 answer

There is a confusion of factors / symbols. The color variable is read in R as a factor, therefore, its basic numerical values ​​are assigned in accordance with the alphabetical order of values: "black" = 1, "blue" = 2 (possibly) "green" = 3, "red" = 4. Then the colors are displayed according to the default R palette: 1 = black, 2 = red, 3 = green, 4 = blue. This leads to (admittedly bizarre) correspondence: “black” = black, “blue” = red, “green” = green, “red” = blue (!!). The fix is ​​actually quite simple: just use as.character around your color variable.

 data.unsorted <- read.table(textConnection( " size qim X1 lower upper color 1 1000 1 100.0000 99.6000 100.0000 blue 2 1000 2 99.8000 99.4000 100.0000 blue 3 1000 3 98.2000 96.6000 99.2000 blue 4 1000 4 62.7000 58.8000 65.7000 blue 5 1000 5 10.4000 9.0000 12.5000 blue 6 1000 6 3.9000 2.9000 4.9000 blue 7 5000 1 99.9000 99.4000 100.0000 red"), header=TRUE) library(gplots) data <- data.unsorted[with(data,order(qim,size)),] 

I will also point out that the with statement makes it easier to read the code and ensures that you get the correct columns:

 with(data[1:2,], plotCI(x=X1,li=lower,ui=upper, col=as.character(color), lty=1,pch=20, xaxt="n", xlim=c(1,42),ylim=c(0,100), gap=0)) 
+6
source

Source: https://habr.com/ru/post/1383523/


All Articles