Luigi Marongiu
2022-Jul-31 13:26 UTC
[R] how to plot with color according to factor keeping a fixed number of levels?
Hello, I am using base R to give color to the points of a graph. I am using the variable Z to provide the value of the color, using the factor of Z. There a supposedly 3 levels of Z. The problem occurs when there only 2 actual levels of Z: in this case, the colors are shifted. In this example, I wanted to color according to the rules Y = 0, then Z = -1 and color = red Y < 1, then Z = 0 and color = blue Y > 1, then Z = 1 and color = green but since there is no Y==0, the colors are shifted because Z has only two levels. How can I keep the original subdivision even if there are fewer levels than expected? Thank you Luigi ``` x = 1:10 y = x*runif(10, 0, 1) z = ifelse(y<1, 1, 0) df = data.frame(X=x, Y=y, Z=z) df$Z[df$Y == 0] = -1 palette(c("red","blue","green")) plot(Y~X, data = df, col = as.factor(Z), pch=16) ```
Ivan Krylov
2022-Jul-31 13:37 UTC
[R] how to plot with color according to factor keeping a fixed number of levels?
On Sun, 31 Jul 2022 15:26:14 +0200 Luigi Marongiu <marongiu.luigi at gmail.com> wrote:> but since there is no Y==0, the colors are shifted because Z has only > two levels.You're almost there: you're already making Z a factor. Use factor(Z, levels = c(-1, 0, 1)) to make a factor with a predefined range of values. -- Best regards, Ivan