R_ggplot2基礎(一)
作者: 李譽輝
四川大學在讀研究生
1 ggplot2特點
-
採用 圖層 的設計方式,有利於結構化思維
-
將表徵資料和圖形細節分開,能快速將圖形表現出來,使創造性繪圖更加容易,而不必糾結於圖形的細節,細節可以後期慢慢調整
-
將常見的統計變換融入到了繪圖中
-
有明確的起始(ggplot開始)與終止(一句話一個圖層),圖層之間的疊加是靠“+”實現的,越往後,其圖層越在上方
-
圖形美觀,擴充套件包豐富,有專門調整字型和公式的包,有專門調整顏色的包,還有專門用按鈕輔助調整主題的包,總之,應有盡有
2 ggplot2基本概念
-
Data資料, Mapping對映
-
Scale標度
-
Geometric幾何物件
-
Statistics統計變換
-
Coordinate座標系統
-
Layer圖層
-
Facet分面
-
Legend圖例
-
beautiful美化
3 ggplot2語法框架
繪圖流程:
ggplot(data, aes(x = , y = )) +# 基礎圖層,不出現任何圖形元素, geom_xxx()|stat_xxx() +# 幾何圖層或統計變換,出現圖形元素 coord_xxx() +# 座標變換,預設笛卡爾座標系 scale_xxx() + # 標度調整,調整具體的標度 facet_xxx() + # 分面,將其中一個變數進行分面變換 guides() + # 圖例調整 theme() # 主題系統
3.1 共性對映與個性對映
-
ggplot(data = NULL, mapping = aes())
-
geom_xxx(data = NULL, mapping = aes())
-
ggplot()
內有data、mapping兩個引數具有全域性優先順序,可以被之後的所有
geom_xxx
物件或stat_xxx()
所繼承(前提是geom
或stat
未指定相關引數) -
而
geom_xxx()
或stat_xxx()
內的引數屬於區域性引數,僅僅作用於內部 -
為了避免混亂,通常將共性對映的引數指定在
ggplot(aes())
aes內部,將個性對映的引數指定在geom_xxx(aes())
或stat_xxx(aes())
內部
3.2 幾何物件與統計變換
-
幾何物件
geom_xxx(stat = )
內有統計變換引數stat
,統計變換stat_xxx(geom = )
內也有幾何物件引數geom
-
兩種方法結果相同,幾何物件更專注於結果,統計變換更專注於變換過程
library(ggplot2) # 用幾何物件作圖 ggplot(data = NULL, mapping = aes(x = x, y = y)) + geom_point(color = "darked", stat = "identity")# identity 表示沒有任何統計變換 # 用統計變換作圖 ggplot(data = NULL, mapping = aes(x = x, y = y)) + stat_identity(color = "darked", geom = "point")# geom_point(stat = 'identity')與stat_identity(geom = 'point')結果一樣
3.3 aes與data引數
-
aes引數用來指定要對映的變數,可以是多個變數,
-
data引數表示指定資料來源,必須是data.frame格式,其座標軸變數最好寬轉長,只能指定一個x軸和y軸,多個x列或y列不能使用調整圖例。
4 geom_xxx()
幾何物件
常用的幾種幾何物件函式:
幾何物件函式描述其它
geom_point點圖geom_point(position = "jitter") == geom_jitter() 避免重疊
geom_line折線圖可以通過smooth引數平滑處理
geom_bar柱形圖x軸是離散變數
geom_area面積圖
geom_histogram直方圖x軸資料是連續的
geom_boxplot箱線圖
geom_rect二維長方形圖
geom_segment線段圖
geom_path幾何路徑由一組點按順序連線
geom_curve曲線
geom_abline斜線有斜率和截距指定
geom_hline水平線常用於座標軸繪製
geom_vline豎線常用於座標軸繪製
geom_text文字
ggplot2唯一不支援的常規平面圖形是 雷達圖
其它幾何物件查詢:
ggplot2 part of the tidyverse
ggplot2 Quick Reference: geom
也可以用
ls(pattern = '^geom_', env = as.environment('package:ggplot2'))
查詢,但是沒有圖形示例
library(ggplot2) ls(pattern = "^geom_", env = as.environment("package:ggplot2"))
柱形圖和散點圖是關鍵,並且與極座標變換緊密相連,著重介紹柱形圖和散點圖,其它的原理和引數都類似
4.1 aesthetics specifications 美學引數
能用作變數 對映 的包括:
美學引數描述
color/col/colour指定點、線和填充區域邊界的顏色
fill指定填充區域的顏色,如條形和密度區域, 第21到24號點也有填充色
alpha指定顏色的透明度,從0(完全透明) 到 1(不透明)
size指定點的尺寸或線的寬度,單位為mm
angle角度,只有部分幾何物件有,如geom_text文字的擺放角度, geom_spoke中短棒擺放角度
linetype指定線條的型別
shape點的形狀, 為[0, 25]區間的26個整數
vjust垂直位置微調,在(0, 1)區間的數字或位置字串: 0=“buttom”, 0.5=“middle”, 1=“top” , 區間外的數字微調比例控制不均
hjust水平位置微調,在(0, 1)區間的數字或位置字串:0=“left”, 0.5=“center”, 1=“right” , 區間外的數字微調比例控制不均
不常對映的引數描述
binwidth直方圖的寬度
notch表示方塊圖是否應為缺口
sides表示地毯圖的安置位置(“b”底部, “l”左部, “t”頂部, “r”右部, “bl”左下角, 等等)
width箱線圖或柱形圖的寬度,從(0, 1), 柱形圖預設0.9即90%
lineend表示指定寬線條端部形狀,有3種:“round”半圓形,“square”增加方形, “butt”預設不變, 常用於geom_path和geom_line幾何物件
family字型(Font face),內建的只有3種:“sans”, “serif”, “mono”
fontface字型,分為: “plain”常規體, “bold”粗體, “italic”斜體, “bold.italic”粗斜體。常用於geom_text等文字物件
lineheight長文字換行行距, 常用於geom_text等文字物件
4.1.1 fill/color 顏色
R自身自持很多種方式的顏色,“顏色名稱”和“HEX色值”最常用和方便,其它的需要擴充套件包
顏色名稱如:
“white”, “azure”, “bisque”, “blue”, “black”, “brown”, “chacolate”, “coral”, “cornsilk”, “cyan”, “gold” ,
“darkgolden”, “orange”, “orchild”, “gray”, “grey”, “tomato”, “violet”, “wheat”, “yellow”, “pink”,
“purple”, “red”, “salmon”, “seashell”, “ivory”,“magentia”,“navy”等系列。
所有的顏色名稱見: R_Color_Chart (後臺回覆: 顏色 ,可下載PDF版本)
如果對一組顏色進行對映的話,建議使用RColorBrewer等調色包,更加方便
RColorBrewer顏色板如下,左邊為字串編號,上下分為3個版塊,分別為漸變色板Sequential,離散對比色板Qualitative,兩極色板Diverging
# colors() # 呼叫所有內建顏色編號,名稱 scales::show_col(colors()[1:6])# show_col函式可以將顏色名稱或HEX色值向量顯示出來 # RColorBrewer包使用 library("RColorBrewer") display.brewer.all()# 顯示所有可用色板 display.brewer.all(type = "seq")# 檢視漸變色板
RColorBrewer使用方法:
通過函式 brewer.pal(n, name)
抽取色條名字為name的n種顏色,後面還可以用“[]”索引符號索取色塊,
一個幾何物件設定多種顏色只能在標度中設定,我們會在標度中繼續講解,例:
library("RColorBrewer") display.brewer.pal(7, "PuRd")# 抽取PuRd色條7種顏色,其顏色色值範圍沒有變,只是色值間隔增大了 display.brewer.pal(9, "PuRd")[11]# 抽取PuRd色條11種顏色,其顏色色值範圍沒有變,指定色值間隔減小了
4.1.2 linetype 線型
線條形狀通過名稱或整數指定:
線型描述
0=“blank”白線
1=“solid”實線
2=“dashed”短虛線
3=“dotted”點線
4=“dotdash”點橫線
5=“longdash”長虛線
6=“twodash”短長虛線
自定義線型
通過1個十六進位制的字串來自定義,字串長度為2、4、6或8。
第1個數字為代表閉合的長度,第2個數字代表缺口的長度,第3個數字又是閉合的長度,第4個數字是缺口的長度,如此交替排列。 然後作為一個整體重複排列
如:
* 字串“33”代表開始3個單位長度閉合,產生短橫線,然後缺口長度也是3個單位,這樣作為一個整體進行重複排列
* 字串“81”代表開始8個單位長度閉合,產生較長的橫線,然後缺口長度為1個單位,這樣作為一個整體重複排列
* 字串“f8”表示開始16個單位長度閉合,產生長橫線,然後缺口長度為8個單位,這樣作為一個整體重複排列
* 字串“357a”表示開始3個單位長度閉合,產生短橫線,然後缺口5個單位,然後閉合7個單位,最後缺口11個單位,這樣整體重複排列
如圖所示:
library(ggplot2) lty <- c("solid", "dashed", "dotted", "dotdash", "longdash", "twodash") linetypes <- data.frame( y = seq_along(lty), # seq_along表示生成與物件同樣長度的序列 lty = lty ) ggplot(linetypes, aes(0, y)) + geom_segment(aes(xend = 5, yend = y, linetype = lty)) +# 將一個變數對映到線型 scale_linetype_identity() + geom_text(aes(label = lty), hjust = 0, nudge_y = 0.2) + scale_x_continuous(NULL, breaks = NULL) + scale_y_reverse(NULL, breaks = NULL) # 自定義線型 lty <- c("33", "18", "81", "f8", "5f", "357a", "5a73", "342167", "a23f45b6") # 自定義9種線型 linetypes <- data.frame( y = seq_along(lty), lty = lty ) ggplot(linetypes, aes(0, y)) + geom_segment(aes(xend = 5, yend = y, linetype = lty)) + # 將一個變數對映到線型 scale_linetype_identity() + geom_text(aes(label = lty), hjust = 0, nudge_y = 0.2) + scale_x_continuous(NULL, breaks = NULL) + scale_y_reverse(NULL, breaks = NULL)
4.1.3 shape點型
[0, 25]個序號代表26種點型, 只有21到26號點形能fill顏色,其它都只有輪廓顏色,
序號32:127對應ASCII字元
所有序號如圖所示:
library("ggplot2") d = data.frame(p = c(0:25, 32:127)) ggplot() + scale_y_continuous(name = "") + scale_x_continuous(name = "") + scale_shape_identity() + geom_point(data = d, mapping = aes(x = p%, y = p%/, shape = p), size = 5, fill = "red") + geom_text(data = d, mapping = aes(x = p%, y = p%/ + 0.25, label = p), size = 3)
4.1.4 family字型
內建的只有3種,可以通過擴充套件包extrafont來將其它字型轉換為ggplot2可識別的標準形式 還可以通過showtext包以圖片的形式將字型插入到ggplot2圖中,對於公式之類的特殊字型特別方便,比Latex容易爆了
library("ggplot2") df <- data.frame(x = c(0.4, 0.6, 0.8), y = 1:3, family = c("sans", "serif", "mono")) ggplot(df, aes(x, y)) + geom_text(aes(label = family, family = family), size = 15) + xlim(0.2, 1) + ylim(0, 4)
4.1.5 Font face字型
分為4類:“plain”常規體, “bold”粗體, “italic”斜體, “bold.italic”粗斜體
library("ggplot2") df <- data.frame(x = c(1, 1.5, 3, 3.5), y = c(2, 1, 1, 2), fontface = c("plain", "bold", "italic", "bold.italic")) ggplot(df, aes(x, y)) + geom_text(aes(label = fontface, fontface = fontface), size = 15) + xlim(0, 5.5) + ylim(0.5, 2.5)
4.1.6 vjust/hjust相對位置微調
vjust: “top” = 1, “middle” = 0.5, “bottom” = 0
hjust: “left” = 0, “center” = 0.5, “right” = 1
微調後,該幾何物件還是在另一個幾何物件周圍
library("ggplot2") just <- expand.grid(hjust = c(0, 0.5, 1), vjust = c(0, 0.5, 1)) just$label <- paste0(just$hjust, ", ", just$vjust) ggplot(just, aes(hjust, vjust)) + geom_point(colour = "grey70", size = 5) + geom_text(aes(label = label, hjust = hjust, vjust = vjust))# 也能進行對映,但很少用
4.2 position adjustment 位置調整引數
包括:
位置調整函式描述其它
position_dodge()水平並列放置position_dodge(width = NULL, preserve = c(“total”, “single”)) 簇狀柱形圖
position_dodge2()水平並列放置position_dodge2(…, padding = 0.1, reverse = FALSE) 簇狀柱形圖,多了2個引數
position_identity()位置不變對於散點圖和折線圖,可行,預設為identity,但對於多分類柱形圖,序列間存在遮蓋
position_stack()垂直堆疊position_stack(vjust = 1, reverse = FALSE) 柱形圖和麵積圖預設stack堆積
position_fill()百分比填充position_fill(vjust = 1, reverse = FALSE) 垂直堆疊,但只能反映各組百分比
position_jitter()擾動處理position_jitter(width = NULL, height = NULL, seed = NA)部分重疊, 用於點圖
position_jitterdodge()並列抖動position_jitterdodge(jitter.width = NULL,jitter.height = 0, dodge.width = 0.75,seed = NA)
position_nudge()整體位置微調position_nudge(x = 0, y = 0),整體向x和y方向平移的距離,常用於geom_text文字物件
position_xxx()
內其它引數:padding, preserve, reverse, vjust, width, height 等
引數名稱值描述
preservec(“total”, “single”)當同一組柱子高度相同時,是保留單個柱子,還是保留所有柱子
padding數字,(0, 1)區間調整柱子間距(中心距離), 越大,則柱子寬度縮小越多, 間距越大,0.5表示寬度縮小50%以增大間距
reverseTRUE/FALSE是否翻轉各組柱子內部的排列順序,對於dodge2則水平順序翻轉,對於stack和fill則垂直順序不同
vjust(0,1)區間調整點和線的垂直位置,預設1頂部,0.5表示居中,0表示處於底部,折線的變化趨勢會變平緩,預設1
width(0,1)區間表示水平抖動的程度,因為存在正負方向,所有抖動的範圍為其2倍,預設0.5
height(0,1)區間表示垂直抖動的程度,因為存在正負方向,所以抖動的範圍為其2倍, 預設0.5
dodge.width(0,1)區間表示各組的點抖動總的水平寬度,預設0.75, 表示點分佈在各組箱子75%寬度上
4.2.1 position_dodge(), position_dodge2() 水平並列
library(ggplot2) ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) + geom_bar(position = "dodge2")# 水平並列柱形圖,預設保留所有柱子 ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) + geom_bar(position = position_dodge(preserve = "total"))# 保留所有柱子 ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) + geom_bar(position = position_dodge(preserve = "single"))# 保留單個柱子 ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) + geom_bar(position = position_dodge2(preserve = "single", reverse = T))# 翻轉各組柱子內部排列順序 ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) + geom_bar(position = position_dodge2(preserve = "single", padding = 0.5))# 所有柱子寬度縮小50%
4.2.2 position_stack, position_fill 垂直堆積
library(ggplot2) ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) + geom_bar()# 柱形圖預設stack堆積 ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) + geom_bar(position = "fill")# 百分比堆積 ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) + geom_bar(position = position_stack(reverse = TRUE))# 翻轉各組內部垂直堆疊順序 # 散點圖 + 折線圖 series <- data.frame(time = c(rep(1, 4), rep(2, 4), rep(3, 4), rep(4, 4)), type = rep(c("a", "b", "c", "d"), 4), value = rpois(16, 10)) ggplot(series, aes(time, value, group = type)) + geom_line(aes(colour = type)) + geom_point(aes(colour = type))# 預設identity ggplot(series, aes(time, value, group = type)) + geom_line(aes(colour = type), position = "stack") + geom_point(aes(colour = type), position = "stack")# stack堆積 ggplot(series, aes(time, value, group = type)) + geom_line(aes(colour = type), position = position_stack(vjust = 0.5)) + geom_point(aes(colour = type), position = position_stack(vjust = 0.5))# 向下移動半個單位,以最下面的元素為高度為基準 ggplot(series, aes(time, value, group = type)) + geom_line(aes(colour = type), position = position_stack(vjust = 0)) + geom_point(aes(colour = type), position = position_stack(vjust = 0))# 向下移動到底,最下面的折線都拉直了
4.2.3 position_jitter(), position_jitterdodge() 擾動錯開
library(ggplot2) ggplot(mtcars, aes(am, vs)) + geom_jitter() ggplot(mtcars, aes(am, vs)) + geom_jitter(width = 0.1, height = 0.1) # 增加水平抖動10%,垂直抖動10% ggplot(mtcars, aes(am, vs)) + geom_point(position = position_jitter(width = 0.1, height = 0.1)) # 原理與上面一樣,但是抖動是隨機的,每次結果都可能不一樣 ggplot(mtcars, aes(am, vs)) + geom_point(position = "jitter") + # 預設抖動50% geom_point(aes(am + 0.2, vs + 0.2), position = "jitter", color = "red" ) # 可以在對映裡面進行簡單的運算
4.2.4 position_jitterdodge()
position_jitterdodge(jitter.width = NULL, jitter.height = 0, dodge.width = 0.75, seed = NA)
僅僅用於箱線圖和點圖在一起的情形,且有順序的,必須箱子在前,點圖在後,抖動只能用在散點幾何物件中,
jitter.width 預設40%, jitter.height 預設0
library(ggplot2) dsub <- diamonds[sample(nrow(diamonds), 1000), ] ggplot(dsub, aes(x = cut, y = carat, fill = clarity)) + geom_boxplot(outlier.size = 0) + geom_point(shape = 23)# 23號點形狀為菱形 ggplot(dsub, aes(x = cut, y = carat, fill = clarity)) + geom_boxplot(outlier.size = 0) + geom_point(shape = 23, position = position_jitterdodge(dodge.width = 0.1))# 點分佈於各組箱子10%寬度上,預設點水平抖動錯開 ggplot(dsub, aes(x = cut, y = carat, fill = clarity)) + geom_boxplot(outlier.size = 0) + geom_point(shape = 23, position = position_jitterdodge(dodge.width = 0.8))# 點分佈於各組箱子80%寬度上,預設點水平抖動錯開
4.2.5 position_nudge 整體微調
library(ggplot2) df <- data.frame(x = c(1, 3, 2, 5), y = c("a", "c", "d", "c")) ggplot(df, aes(x, y)) + geom_point() + geom_text(aes(label = y))# 文字物件位置與點重合,視覺效果不好 ggplot(df, aes(x, y)) + geom_point() + geom_text(aes(label = y), position = position_nudge(y = -0.1))# 文字位置向下移動1%個單位,錯開文字與點位置
公眾號後臺回覆關鍵字即可學習
回覆 爬蟲 爬蟲三大案例實戰
1小時破冰入門
回覆 資料探勘 R語言入門及資料探勘
回覆 人工智慧 三個月入門人工智慧
回覆 資料分析師 資料分析師成長之路
回覆 機器學習 機器學習的商業應用
回覆 資料科學 資料科學實戰
常用演算法
常用資料探勘演算法

本文由R語言中文社群 創作,採用 ofollow,noindex">知識共享署名-相同方式共享 3.0 中國大陸許可協議 進行許可。
轉載、引用前需聯絡作者,並署名作者且註明文章出處。
本站文章版權歸原作者及原出處所有 。內容為作者個人觀點, 並不代表本站贊同其觀點和對其真實性負責。本站是一個個人學習交流的平臺,並不用於任何商業目的,如果有任何問題,請及時聯絡我們,我們將根據著作權人的要求,立即更正或者刪除有關內容。本站擁有對此宣告的最終解釋權。