When to use factor () when plotting with ggplot in R?

When do you usually use factorfor coding color / size variables in ggplot2 in R? Example:

ggplot(mtcars) + geom_point(aes(x=mpg, y=drat, colour=gear))

against

ggplot(mtcars) + geom_point(aes(x=mpg, y=drat, colour=factor(gear)))

Is it a general rule to use factorwhen a variable used to define shape / size / color is discrete and not continuous? Or is there another use factorin this context? It seems that the first team can be made as the second with the right legend, even without factor. thank.

edit: I get this when I use colour=gear: enter image description here

+5
source share
1 answer

The problem is not in the legend, but in the choice of colors. When this is not a factor, the dots have different shades of the same hue:

ggplot(mtcars) + geom_point(aes(x=mpg, y=drat, colour=gear))

enter image description here

, . (, , ).

gears , :

ggplot(mtcars) + geom_point(aes(x=mpg, y=drat, colour=factor(gear)))

enter image description here

: , factor, ggplot2.

+6

All Articles