chooseCRANmirror(graphics=FALSE, ind=1)
knitr::opts_chunk$set(echo = TRUE)
“+” “%+%”
将组件添加到绘图中
+ 是构建复杂的ggplot2图形的关键,它允许你从简单开始,然后一步步绘制比较复杂的图
## S3 method for gg
# +(e1 + e2)
# e1 %+% e2
元素
(这里就不做翻译了,通俗易懂)
e1 An object of class ggplot() or a theme()
e2 A plot component, as described below
You can add any of the following types of objects:
> An aes() object replaces the default aesthetics. (添加一个aes,替代默认的aes)
> A layer created by a geom_ or stat_ function adds a new layer. (在原图层(原图层由geom或stat构建)的基础上添加一个新图层)
> A scale overrides the existing scale. (覆盖当前的标度)
> A theme() modifies the current theme. (修改当前主题)
> A coord overrides the current coordinate system. (覆盖当前坐标)
> A facet specification overrides the current faceting. (一个新的分面规格覆盖当前的分面)
注意如果要替换当前的默认数据框,需要用%+%
你还可以提供列表,在这种情况下,列表的每个元素将依次添加。
例子
library(ggplot2)
base=ggplot(mpg,aes(displ,hwy))+geom_point()
base

base+geom_smooth()
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'

# "geom_smooth()" using method ='loess' and formula 'y ~ x'
# To override the data, you must use %+%
base %+% subset(mpg,fl == "p")

# Alternatively, you can add multiple components with a list.
# This can be useful to return from a function.
base + list(subset(mpg, fl=="p"),geom_smooth())
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'
