# [R] how to plot with color according to factor keeping a fixed number of levels?

Luigi Marongiu m@rong|u@|u|g| @end|ng |rom gm@||@com
Sun Jul 31 15:26:14 CEST 2022

```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)
```

```