ggplot2基礎(chǔ)(3)——注釋
ggplot2基礎(chǔ)(1)
ggplot2基礎(chǔ)(2)——坐標(biāo)軸
ggplot2基礎(chǔ)(3)——注釋
ggplot2基礎(chǔ)(4)——主題
ggplot2基礎(chǔ)(5)——配色與圖例
使用ggplot2過(guò)程中,離不開在其中添加各種各樣的文字信息,對(duì)于坐標(biāo)軸上的文字內(nèi)容,可以使用的函數(shù)包括lab()、xlab()、ylab等多個(gè)函數(shù),我們已經(jīng)在上一章中進(jìn)行了詳細(xì)的介紹,這一章我們主要介紹圖中的其他文字標(biāo)注方式——注釋。
參考的內(nèi)容主要是:
- 《R數(shù)據(jù)可視化手冊(cè)》
- 《R繪圖 第十篇:繪制文本、注釋和主題(ggplot2)》
- 《R可視化05|ggplot2圖層-注釋圖層(Annotation layer)》
- 《Create an annotation layer》
- 《8 Annotations》
1 annotate函數(shù)
如果想要在圖片上添加注釋,目前比較推薦的是使用annotate函數(shù),該函數(shù)會(huì)在圖片上增加注釋圖層,該圖層不會(huì)映射到DataFrame對(duì)象。其定義為:
annotate(
geom,
x = NULL,
y = NULL,
xmin = NULL,
xmax = NULL,
ymin = NULL,
ymax = NULL,
xend = NULL,
yend = NULL,
vjust,
hjust,
arrow = NULL,
parse = FALSE,
...,
na.rm = FALSE
)
其中
-
geom注釋的類型,可選項(xiàng)包括"text"(文本)、"rect"(矩形)、"segment"(線段)、"pointrange"(點(diǎn)線段)、"curve"(曲線)等 -
x, y, xmin, ymin, xmax, ymax, xend, yend, vjust, hjust注釋所在的位置信息 -
arrow設(shè)置箭頭信息(只有注釋類型為線段或曲線時(shí)起作用) -
parse邏輯型參數(shù);若設(shè)為TRUE,則label參數(shù)的內(nèi)容遵循plotmath的編譯規(guī)則 -
...一些視覺(jué)參數(shù),可以參考aes函數(shù)的設(shè)置 -
na.rm默認(rèn)值為FALSE,此時(shí)缺失的值會(huì)被移除,并會(huì)給出警告信息;如果設(shè)置為TRUE,則缺失值會(huì)被刪除而不給出任何警告信息。
1.1 文本型注釋——text
使用文本型注釋,除了將geom參數(shù)設(shè)置為text外,還需要設(shè)置label參數(shù):
library(ggplot2)
p = ggplot(faithful, aes(x=eruptions, y=waiting)) +
geom_point()
p + annotate("text", x=3, y=48, label="Group1") +
annotate("text", x=4.5, y=66, label="Group2")

如果坐標(biāo)軸為連續(xù)值,則可以將x、y設(shè)置為Inf或-Inf,以便于在繪圖區(qū)域的邊緣放置注解。
p +
annotate("text", x=-Inf, y=Inf, label="Upper left", hjust=-.2, vjust=2) +
annotate("text", x= mean(range(faithful$eruptions)), y=-Inf, vjust=-0.4, label="Bottom middle")

此外,還可以在label中使用Latex公式(其實(shí)是plotmath),以實(shí)現(xiàn)公式的編輯(同時(shí)將parse參數(shù)設(shè)置為TRUE)。如果需要在公式中使用普通的文字,則需要在其中將普通文字以單引號(hào)引起來(lái),同時(shí)添加*作為分隔。
p = ggplot(data.frame(x=c(-3, 3)), aes(x=x)) +
stat_function(fun=dnorm)
p + annotate("text", x=0, y=0.05, size=4, parse=TRUE, label="'Function:' * y==frac(1, sqrt(2 * pi)) * e^{-x^2/2}")

1.2 線型注釋(含箭頭)——segment、curve
如果要在圖片中添加線段型注釋,則需要將geom設(shè)置為"segment",同時(shí)設(shè)置x、y、xend、yend,分別代表起點(diǎn)和終點(diǎn)的坐標(biāo)
如果要為線段添加箭頭,則需要設(shè)置arrow參數(shù)
arrow參數(shù)一般使用arrow()函數(shù)來(lái)進(jìn)行設(shè)置,其常用的參數(shù)有:
- ends 如果設(shè)置為
"both",則表示線段的兩邊均有箭頭,否則只在線段的終端進(jìn)行設(shè)置 - angel 箭頭的角度,如果設(shè)置為90,則可以作為范圍的標(biāo)簽進(jìn)行使用
- length 箭頭的長(zhǎng)度,一般可以使用
unit(長(zhǎng)度,"單位")的形式來(lái)使用
更多的使用可以加載
grid包后,用?arrow命令來(lái)查看
p <- ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point()
p + annotate("segment", x = 2.5, xend = 4, y = 15, yend = 25, color = "blue", size=4)

p <- ggplot(mpg, aes(displ, hwy)) +
geom_point(
data=filter(mpg, manufacturer=="subaru"),
color="orange",
size=3,
) +
geom_point()
p +
annotate(geom = "segment", x = 4, y = 35, xend = 2.65, yend = 27, arrow = arrow(length = unit(4, "mm")), size=2)+
annotate(geom = "text", x = 4.1, y = 35, label = "subaru", hjust = "left", size=10)

當(dāng)需要使用更加美觀的曲線時(shí),需要將geom設(shè)置為"curve",同時(shí)想要調(diào)整曲線的曲率,則可以調(diào)整curvature參數(shù)。
p +
annotate(geom = "curve", x = 4, y = 35, xend = 2.65, yend = 27, curvature = .3, arrow = arrow(length = unit(4, "mm")), size=2)+
annotate(geom = "text", x = 4.1, y = 35, label = "subaru", hjust = "left", size=10)

1.3 陰影注釋——rect
使用陰影注釋(在圖片中添加矩形方框),除了需要將geom參數(shù)設(shè)置為"rect"外,還需要設(shè)置好xmin、ymin、xmax、ymax,以便于確定矩形的范圍。
ggplot(economics) +
geom_line(aes(date, unemploy)) +
annotate("rect",
xmin=as.Date("1970-01-01","%Y-%m-%d"),
xmax=as.Date("1979-12-31","%Y-%m-%d"),
ymin=-Inf, ymax=Inf, fill="blue", alpha=.1)+
xlab("date") +
ylab("unemployment")

2 其他注釋
2.1 直線注釋
前面提到的是線段注釋,如果想要使用直線類型的注釋,可選的選項(xiàng)包括:
- geom_hline()
- geom_vline()
- geom_abline()
其中g(shù)eom_abline()的參數(shù)主要包括:
- slope 表示斜率
- intercept 表示截距
早期的ggplot中并未包含annotate函數(shù),因此絕大多數(shù)使用的是直線、geom_rect等對(duì)象進(jìn)行注釋
library(ggplot2)
p = ggplot(mpg, aes(displ, hwy, colour = class)) +
geom_point()
p +
geom_hline(yintercept=25) +
geom_vline(xintercept=3) +
geom_abline(slope=3, intercept=20)

2.2 文字注釋——geom_text與geom_label
使用geom_text()和geom_label()也可以在圖中添加文字,進(jìn)而實(shí)現(xiàn)注釋的效果。但是需要注意的是,當(dāng)使用這兩個(gè)函數(shù)時(shí),會(huì)在圖中增加一個(gè)文字圖層,同時(shí)該圖層會(huì)映射到DataFrame中。例如,在下面的例子中,文字"Group 1"是我們使用annotate()函數(shù)繪制的,我們將其透明度設(shè)置為0.1,而"Group 2"是我們使用geom_text()函數(shù)繪制的,在繪制時(shí),我們同樣將其透明度設(shè)置為0.1,但是由于geom_text函數(shù)對(duì)DataFrame數(shù)據(jù)(即faithful)的映射,因此"Group 2"被繪制了n次,因此盡管其透明度也被設(shè)置為0.1,但是其清晰度則遠(yuǎn)遠(yuǎn)高于"Group 1"。
此外需要注意的是相對(duì)于geom_text而言,geom_label會(huì)在文本周圍添加一個(gè)背景
library(ggplot2)
p = ggplot(faithful, aes(x=eruptions, y=waiting)) +
geom_point()
p + annotate("text", x=3, y=48, label="Group1", alpha=0.1) +
geom_text(x=4.5, y=66, label="Group2", alpha=0.1)

3 分面注釋
在分面上添加注釋的方法有很多種,最主要還是依賴于要表達(dá)的信息:
3.1 方法一
使用分面變量創(chuàng)建一個(gè)新的數(shù)據(jù)框,然后設(shè)定每個(gè)分面需要繪制的值,最后配合新的數(shù)據(jù)框使用geom_text()函數(shù)
mpg_plot <- ggplot(mpg, aes(x = displ, y = hwy)) +
geom_point() +
facet_grid(. ~ drv)
f_labels = data.frame(drv=c("4", "f", "r"), label=c("4wd", "Front", "Rear"))
mpg_plot +
geom_text(x=6, y=40, mapping=aes(label=label), data=f_labels)

lm_labels <- function(dat) {
mod <- lm(hwy ~ displ, data = dat)
formula <- sprintf("italic(y) == %.2f %+.2f * italic(x)",
round(coef(mod)[1], 2), round(coef(mod)[2], 2))
r <- cor(dat$displ, dat$hwy)
r2 <- sprintf("italic(R^2) == %.2f", r^2)
data.frame(formula = formula, r2 = r2, stringsAsFactors = FALSE)
}
library(dplyr)
labels <- mpg %>%
group_by(drv) %>%
do(lm_labels(.))
mpg_plot +
geom_smooth(method=lm, se=FALSE) +
geom_text(data=labels, aes(label=formula), x=3, y=40, parse=TRUE) +
geom_text(x=3, y=35, aes(label=r2), data=labels, parse=TRUE, hjust=0)

3.2 方法二
使用gghighlight包
# install.packages("gghighlight")
ggplot(mpg, aes(displ, hwy, colour = factor(cyl))) +
geom_point() +
gghighlight::gghighlight() +
facet_wrap(.~factor(cyl))
