在R中用ggplot进行绘图时何时使用factor()? [英] when to use factor() when plotting with ggplot in R?
问题描述
通常何时使用factor
对R中的ggplot2中的变量进行着色/调整大小?示例:
When do you normally use factor
to color/size encode variables in ggplot2 in R? Example:
ggplot(mtcars) + geom_point(aes(x=mpg, y=drat, colour=gear))
与之相对:
ggplot(mtcars) + geom_point(aes(x=mpg, y=drat, colour=factor(gear)))
当用于确定形状/大小/颜色的变量是离散的而不是连续的时,一般规则是否使用factor
?还是在这种情况下还有factor
的其他用法?即使没有factor
,似乎第一个命令也可以像第二个命令一样带有正确的图例.谢谢.
Is the general rule to use factor
when the variable being used to determine the shape/size/colour is discrete, and not continuous? Or is there another use of factor
in this context? It seems like the first command can be made like the second with the right legend, even without factor
. thanks.
edit :使用colour=gear
时,我得到了以下信息:
edit: I get this when I use the colour=gear
:
推荐答案
问题不是传说,而是颜色的选择.当不是一个因素时,这些点是同一色调的不同阴影:
The issue isn't the legend, it's the choice of colors. When it is not a factor, the points are different shades of the same hue:
ggplot(mtcars) + geom_point(aes(x=mpg, y=drat, colour=gear))
这传达了一个连续的点,因此对于一组单独的可能性而言并不理想. (实际上,一旦您获得五到六种可能性,颜色可能很难彼此区分.)
This communicates a continuum of points, and it's thus not ideal for a set of separate possibilities. (Indeed, once you get to five or six possibilities the colors can be hard to distinguish from each other).
当将gears
当作一个因素对待时,颜色会被选择为可区分的:
When gears
is treated like a factor, the colors are chosen to be distinguishable:
ggplot(mtcars) + geom_point(aes(x=mpg, y=drat, colour=factor(gear)))
请注意,如果在不使用factor
时未得到渐变图,则应尝试升级到ggplot2
的最新版本.
Note that if you're not getting a gradient plot when not using factor
, you should try upgrading to a more recent version of ggplot2
.
这篇关于在R中用ggplot进行绘图时何时使用factor()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!