Colour difference in plot between normal variable and factor variable

I am using plot function on mtcars dataset.

I am trying to add colour to the plots based on mtcars$cyl variable

The distinct values in cyl variable is 4,6 and 8

First i tried this:

plot(x=mtcars$wt, y=mtcars$mpg, col = mtcars$cyl)

I got points plotted on blue,purple and grey colour.

Then I converted cyl variable into a factor and tried the same plot again,

mtcars$fcyl <- as.factor(mtcars$cyl)

plot(x=mtcars$wt, y=mtcars$mpg, col = mtcars$fcyl)

But this time I got black,red and green

I want to understand how assigning the variable as factor changes the colour. What happens behind?


I want to understand how assigning the variable as factor changes the colour. What happens behind?

In R, factors are just integers under the hood. In the plot function, integers are converted to eight different colors (repeating), which are 8 colors that can be visually separated.

Try this:

plot(x=1:16, y=1:16, col = 1:16, pch=16)
链接地址: http://www.djcxy.com/p/30970.html

上一篇: 点击不会从模板中触发

下一篇: 正常变量和因子变量之间的图中的颜色差异