R語言之視覺化(20)之geom_label()和geom_text()
目錄
R語言之視覺化①誤差棒
R語言之視覺化②點圖
R語言之視覺化③點圖續
R語言之視覺化④點韋恩圖upsetR
R語言之視覺化⑤R圖形系統
R語言之視覺化⑥R圖形系統續
R語言之視覺化⑦easyGgplot2散點圖
R語言之視覺化⑧easyGgplot2散點圖續
R語言之視覺化⑨火山圖
R語言之視覺化⑩座標系統
R語言之視覺化①①熱圖繪製heatmap
R語言之視覺化①②熱圖繪製2
R語言之視覺化①③散點圖+擬合曲線
R語言之視覺化①④一頁多圖(1)
R語言之視覺化①⑤ROC曲線
R語言之視覺化①⑥一頁多圖(2)
R語言之視覺化①⑦調色盤
R語言之視覺化①⑧子圖組合patchwork包
R語言之視覺化①⑨之ggplot2中的圖例修改
R語言之視覺化(20)之geom_label()和geom_text()
Geom_text()將文字直接新增到繪圖中。 geom_label()在文字後面繪製一個矩形,使其更易於閱讀。
示例
p <- [ggplot](mtcars, aes(wt, mpg, label = rownames(mtcars))) p + geom_text()

image
避免字型重疊
p + geom_text(check_overlap = TRUE)

image
給label加上背景
p + geom_label()

image
修改字型大小
p + geom_text(size = 10)

image
p + geom_point () + geom_text(hjust = 0, nudge_x = 0.05)

image
p + geom_point () + geom_text(vjust = 0, nudge_y = 0.5)

image
p + geom_point () + geom_text(angle = 45)

image
新增對映
p + geom_text( aes (colour = factor (cyl)))

image
p + geom_text( aes (colour = factor (cyl))) +
scale_colour_discrete (l = 40)

image
p + geom_label( aes (fill = factor (cyl)), colour = "white", fontface = "bold")

image
p + geom_text( aes (size = wt))

image
縮放文字高度
p + geom_text( aes (size = wt)) + scale_radius (range = c (3,6))

image
可以通過設定parse = TRUE來顯示錶達式。themama中描述了顯示的詳細資訊,但請注意geom_text使用字串,而不是表示式。
p + geom_text( aes (label = paste (wt, "^(", cyl, ")", sep = "")),
parse = TRUE)

image
新增一個註釋
p +geom_text() + annotate ("text", label = "plot mpg vs. wt", x = 2, y = 15, size = 8, colour = "red")

image
對齊標籤和條形
df <- data.frame (
y = c (1, 3, 2, 1),
grp = c ("a", "b", "a", "b")
)
ggplot2不知道你想給標籤賦予相同的虛擬寬度
ggplot (data = df, aes (x, y, group = grp)) +
geom_col ( aes (fill = grp), position = "dodge") +
geom_text( aes (label = y), position = "dodge")

image
ggplot (data = df, aes (x, y, group = grp)) +
geom_col ( aes (fill = grp), position = "dodge") +
geom_text( aes (label = y), position = position_dodge (0.9))

image
#使用你無法輕推和躲避文字,所以改為調整y位置
ggplot (data = df, aes (x, y, group = grp)) +
geom_col ( aes (fill = grp), position = "dodge") +
geom_text(
aes (label = y, y = y + 0.05),
position = position_dodge (0.9),
vjust = 0
)

image
如果將文字放在堆積的條形圖中每個條形圖的中間,需要設定position_stack()的vjust引數
ggplot (data = df, aes (x, y, group = grp)) +
geom_col ( aes (fill = grp)) +
geom_text( aes (label = y), position = position_stack (vjust = 0.5))

image