在ggplot中我们说上面两图用不同的几何体表示,geom是几何对象,例如条形图使用bar geoms,折线图使用line geoms,箱线图使用boxplot geoms等等。你可以使用不同的几何体来描绘同一个数据。
要更改图中的geom,请使用ggplot()中的geom函数。例如要画上面的图,代码为
# left
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy))
# right
ggplot(data = mpg) +
geom_smooth(mapping = aes(x = displ, y = hwy))
ggplot中的每个geom函数都有一个映射参数。你可以设置点的形状,但不能设置线的形状。另一方面,你可以设置线的线形(linetype).
ggplot(data = mpg) +
geom_smooth(mapping = aes(x = displ, y = hwy, linetype = drv))
geom_smooth() will draw a different line, with a different linetype, for each unique value of the variable that you map to linetype.
此处geom_smooth()根据汽车的drv值将汽车分成三行,该值描述了汽车的动力传动系统。这里4代表4轮驱动,f代表前轮驱动,r代表后轮驱动。
ggplot2 提供了 40 多个 geoms,扩展包提供了更多(请参阅 https://exts.ggplot2.tidyverse.org/gallery/ 以获取示例)。获得全面概览的最佳方式是 ggplot2 备忘单,您可以在 http://rstudio.com/resources/cheatsheets 上找到它。要了解有关任何单个 geom 的更多信息,请使用帮助:?geom_smooth。
许多geoms,比如geom_smooth(),使用单个几何对象来显示多行数据。对于这些几何图形,您可以将组美学设置为分类变量以绘制多个对象。 ggplot2 将为分组变量的每个唯一值绘制一个单独的对象。在实践中,每当您将美学映射到离散变量(如线型示例中)时,ggplot2 将自动对这些几何图形的数据进行分组。依靠此功能很方便,因为组美学本身不会向几何图形添加图例或区别特征。
ggplot(data = mpg) +
geom_smooth(mapping = aes(x = displ, y = hwy))
ggplot(data = mpg) +
geom_smooth(mapping = aes(x = displ, y = hwy, group = drv))
ggplot(data = mpg) +
geom_smooth(
mapping = aes(x = displ, y = hwy, color = drv),
show.legend = FALSE
)
要在同一个图中显示多个geom,请向ggplot()添加多个geom函数。
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
geom_smooth(mapping = aes(x = displ, y = hwy))
但像上面这样写代码,会引起一些重复。 比如想在y轴展示cty而不是hwy,你就需要在两个地方更改变量,而你可能忘记更新其中一个。你可以用一组映射传递给ggplot()来避免这种类型的重复。
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point() +
geom_smooth()
这个代码将生成和上面代码一样的图。
如果将映射放在geom内,ggplot会将它视为图层的本地映射。它将仅使用该映射来扩展或者覆盖该层的全局映射。这使得可以在不同的层中展示不同的aesthetics
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point(mapping = aes(color = class)) +
geom_smooth()
您可以使用相同的想法为每个图层指定不同的数据。下面的代码中, 平滑线仅显示mpg数据集的一个子集,即小型汽车。geom_smooth() 中的本地数据参数仅覆盖该层的 ggplot() 中的全局数据参数。
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point(mapping = aes(color = class)) +
geom_smooth(data = filter(mpg, class == "subcompact"), se = FALSE)