第一部分 探索
第1章 使用ggplot2進(jìn)行數(shù)據(jù)可視化
1.1 簡(jiǎn)介
首先安裝并加載R包(ggplot2)
if(!require('ggplot2'))install.packages('ggplot2')
library('ggplot2')
我們下面使用ggplot2去探索一個(gè)問題:大引擎汽車比小引擎汽車更耗油嗎毙籽?
1.2 第一步
1.2.1 mpg數(shù)據(jù)框
該數(shù)據(jù)框是ggplot2內(nèi)置的一個(gè)數(shù)據(jù)集供我們學(xué)習(xí)使用∠锊椋可以自己查看下mpg數(shù)據(jù)集中包含哪些東西及結(jié)構(gòu):使用(?mpg)
mpg
#> # A tibble: 234 x 11
#> manufacturer model displ year cyl trans drv cty hwy fl class
#> <chr> <chr> <dbl> <int> <int> <chr> <chr> <int> <int> <chr> <chr>
#> 1 audi a4 1.8 1999 4 auto(l5) f 18 29 p compa…
#> 2 audi a4 1.8 1999 4 manual(m5) f 21 29 p compa…
#> 3 audi a4 2 2008 4 manual(m6) f 20 31 p compa…
#> 4 audi a4 2 2008 4 auto(av) f 21 30 p compa…
#> 5 audi a4 2.8 1999 6 auto(l5) f 16 26 p compa…
#> 6 audi a4 2.8 1999 6 manual(m5) f 18 26 p compa…
#> # … with 228 more rows
以下整理了mpg數(shù)據(jù)集具體參數(shù)含義
名稱 | 含義 |
---|---|
manufacturer | manufacturer name(車的制造商名稱幢妄,如:奧迪) |
model | model name(車的型號(hào)性誉,如:A6) |
displ | engine displacement, in litres(發(fā)動(dòng)機(jī)排量即引擎大小岳服,單位升) |
year | year of manufacture(車的制造年份) |
cyl | number of cylinders(汽缸數(shù)) |
trans | type of transmission(變速箱類型) |
drv | the type of drive train, where f = front-wheel drive, r = rear wheel drive, 4 = 4wd(驅(qū)動(dòng)類型矿筝,f=前輪驅(qū)動(dòng)猛们,r=后輪驅(qū)動(dòng)念脯,4=四驅(qū)) |
cty | city miles per gallon(每加侖油在城市跑的里程數(shù)) |
hwy | highway miles per gallon(高速公路每加侖行駛里程數(shù)) |
fl | fuel type(燃料類型) |
class | "type" of car(汽車類型,如:轎車弯淘、suv等) |
1.2.2 創(chuàng)建ggplot圖形
x軸放displ绿店,y軸放hwy
ggplot(data = mpg)+
geom_point(mapping = aes(x = displ, y = hwy))
這圖可以看出來引擎越大,同樣體積的油跑的里程越少耳胎。即引擎越大越耗油(displ與hwy負(fù)相關(guān))
在ggplot2中畫圖:
1惯吕、使用ggplot()函數(shù)開始繪圖,該函數(shù)創(chuàng)建了一個(gè)坐標(biāo)系怕午,你可以在它上面添加圖層废登。ggplot()第一個(gè)參數(shù)是data,即圖中要使用的數(shù)據(jù)集郁惜。
2堡距、向ggplot()中添加一個(gè)或多個(gè)圖層就可以完成這張圖了。函數(shù)geom_point()是向圖中添加一個(gè)點(diǎn)層兆蕉,這樣就可以創(chuàng)建一張散點(diǎn)圖了羽戒。這種叫做幾何對(duì)象函數(shù)(geom function)。
3虎韵、每個(gè)幾何對(duì)象函數(shù)(geom function)都有一個(gè)mapping參數(shù)易稠。這個(gè)參數(shù)定義了如何將數(shù)據(jù)集中的變量映射為圖形屬性。mapping參數(shù)總和aes()函數(shù)成對(duì)出現(xiàn)包蓝,aes()函數(shù)的x參數(shù)和y參數(shù)分別指定了映射到x和y軸的變量驶社。
ggplot2繪圖理念為plot(圖形)=data(數(shù)據(jù)集)+geometry(幾何對(duì)象)+aesthetics(美學(xué)映射)
繪圖模板:
# 將<>內(nèi)的內(nèi)容分別替換為數(shù)據(jù)集企量、幾何對(duì)象函數(shù)和映射集合即可
ggplot(data = <DATA>)+
<GEOM_FUNCTION>(mapping = aes(<MAPPINGS>))
1.3 圖形屬性映射
本章首先要了解變量類型。
1、aes() 將圖層中使用的每個(gè)圖形屬性映射集合在一起,然后傳遞給該圖層的映射參數(shù)慢哈。
2、想要手動(dòng)設(shè)置圖形的屬性函似,需要按照名稱進(jìn)行設(shè)置,將其作為幾何對(duì)象函數(shù)的一個(gè)參數(shù),即在函數(shù)aes()的外部進(jìn)行設(shè)置
3、點(diǎn)的形狀是一個(gè)數(shù)值瘾英。空心形狀(0-14)的邊界顏色由color決定孝凌;實(shí)心形狀(15-20)的填充顏色由color決定方咆;填充形狀(21-24)的邊界顏色由color決定月腋,填充顏色由fill決定蟀架。
<img src="https://gitee.com/yahangliang/typoraimage/raw/master/20210510193603.png" alt="11" style="zoom:67%;" />
練習(xí):
一、以下這段代碼有什么錯(cuò)誤榆骚?為什么點(diǎn)不是藍(lán)色的片拍?
ggplot(data = mpg) +
geom_point(
mapping = aes(x = displ, y = hwy, color = "blue")
)
把"blue"換成mpg中的變量drv對(duì)比看下
p1 <- ggplot(data = mpg) +
geom_point(
mapping = aes(x = displ, y = hwy, color = "blue")
)
p2 <- ggplot(data = mpg) +
geom_point(
mapping = aes(x = displ, y = hwy, color = drv))
p1+p2
第一個(gè)代碼的錯(cuò)誤就是我們本節(jié)開頭的第2點(diǎn)所說的內(nèi)容。
二妓肢、mpg 中的哪些變量是分類變量捌省?哪些變量是連續(xù)變量?(提示:輸入?mpg 來閱讀這個(gè)數(shù)據(jù)集的文檔碉钠。)當(dāng)調(diào)用mpg 時(shí)纲缓,如何才能看到這些信息?
分類變量包括:manufacturer喊废、model祝高、trans、drv污筷、fl工闺、class
連續(xù)變量包括:displ、year瓣蛀、cyl陆蟆、cty、hwy
有一個(gè)捷徑:把變量映射給 shape 參數(shù)惋增,如果是連續(xù)變量就會(huì)報(bào)錯(cuò)叠殷,分類變量就不會(huì)。
另外可以使用命令 View(mpg) 來查看mpg數(shù)據(jù)集诈皿。
三林束、將一個(gè)連續(xù)變量映射為 color钩杰、size 和 shape。對(duì)分類變量和連續(xù)變量來說诊县,這些圖形屬性的表現(xiàn)有什么不同讲弄?
我們這里連續(xù)變量用year,分類變量用model依痊;然后分別映射到color避除、size 和 shape。
(1)color
p1 <- ggplot(data = mpg) +
geom_point(
mapping = aes(x = displ, y = hwy, color = year)
)
p2 <- ggplot(data = mpg) +
geom_point(
mapping = aes(x = displ, y = hwy, color = model))
p1+p2
(2) size
p1 <- ggplot(data = mpg) +
geom_point(
mapping = aes(x = displ, y = hwy, size = year)
)
p2 <- ggplot(data = mpg) +
geom_point(
mapping = aes(x = displ, y = hwy, size = model))
p1+p2
## Warning message:
## Using size for a discrete variable is not advised.
這個(gè)警告的意思是我們把model這個(gè)離散型變量賦給size不建議(model明明是無序分類變量胸嘁,不知道這里為啥提示它是離散型變量瓶摆?)
(3)shape
p1 <- ggplot(data = mpg) +
geom_point(
mapping = aes(x = displ, y = hwy, shape = year)
)
# 錯(cuò)誤: A continuous variable can not be mapped to shape
p2 <- ggplot(data = mpg) +
geom_point(
mapping = aes(x = displ, y = hwy, shape = model))
p2
連續(xù)型變量賦值給shape會(huì)報(bào)錯(cuò),分類變量可以賦值給shape性宏,但系統(tǒng)最多支持6中shape所以圖中可以看到只顯示了6種群井。
四、如果將同一個(gè)變量映射為多個(gè)圖形屬性毫胜,會(huì)發(fā)生什么情況书斜?
ggplot(data = mpg) +
geom_point(
mapping = aes(x = displ, y = hwy, size = hwy, color = hwy))
信息出現(xiàn)了多余,圖中點(diǎn)的大小和顏色深淺都可以反應(yīng)每個(gè)車的hwy屬性酵使。
五荐吉、stroke 這個(gè)圖形屬性的作用是什么?它適用于哪些形狀口渔?(提示:使用?geom_point 命令样屠。)
p1 <- ggplot(data = mpg) +
geom_point(
mapping = aes(x = displ, y = hwy),
shape = 0 # 0 代表空心正方形
)
p2 <- ggplot(data = mpg) +
geom_point(
mapping = aes(x = displ, y = hwy),
shape = 0 ,stroke = 3 # 0 代表空心正方形
)
p1 + p2
我們我可以看出參數(shù)stroke代表的是圖形屬性:邊框的寬度缺脉。
六痪欲、如果將圖形屬性映射為非變量名對(duì)象,比如 aes(color = displ < 5)攻礼,會(huì)發(fā)生什么情況业踢?
ggplot(data = mpg) +
geom_point(
mapping = aes(x = displ, y = hwy, color = displ < 5))
顏色分為兩類一類displ<5,另一類displ>=5秘蛔。
1.4 常見問題
多google/bing/簡(jiǎn)書/微信/語雀搜索找答案陨亡,你遇到的大多數(shù)問題,很多人早就遇到過并且有大神已經(jīng)回復(fù)解答了深员。
1.5 分面
如果數(shù)據(jù)集種的變量是連續(xù)型變量我們可以通過映射的方式添加到圖形屬性即在aes()函數(shù)內(nèi)寫上负蠕。若變量是分類變量,那我們可以采用分面的方式倦畅,即顯示數(shù)據(jù)子集的子圖遮糖。
facet_wrap()第一個(gè)參數(shù)是一個(gè)公式,創(chuàng)建方式為~后面加一個(gè)變量名或vars(變量叠赐,變量欲账,變量屡江,。赛不。惩嘉。)
facet_grid()第一個(gè)參數(shù)是一個(gè)公式,創(chuàng)建方式為由~隔開的兩個(gè)變量名或
練習(xí):
一踢故、如果使用連續(xù)變量進(jìn)行分面文黎,會(huì)發(fā)生什么情況?
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy))+
facet_wrap(~cty)
按照連續(xù)型變量分別展示數(shù)據(jù)沒什么意義殿较。根本看不出數(shù)據(jù)分布的規(guī)律耸峭、
二、在使用facet_grid(drv ~ cyl) 生成的圖中淋纲,空白單元的意義是什么劳闹?它們和以下代碼生成的圖有什么關(guān)系?
ggplot(data = mpg) +
geom_point(mapping = aes(x = drv, y = cyl))
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy))+
facet_grid(drv ~ cyl)
空白代表此處沒有對(duì)應(yīng)的數(shù)據(jù)洽瞬。兩圖是一一對(duì)應(yīng)的關(guān)系本涕,上圖的每個(gè)點(diǎn)對(duì)應(yīng)下圖的每個(gè)面。
三片任、 以下代碼會(huì)繪制出什么圖偏友? . 的作用是什么蔬胯?
p1 <- ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_grid(drv ~ .)
p2 <- ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_grid(. ~ cyl)
p1 + p2
.代表不行這里分面对供。如:drv ~ .代表在行維度上以drv分面,列維度不分面氛濒。. ~cyl代表在行維度不分面产场,列維度以cyl分面。
四舞竿、查看本節(jié)的第一個(gè)分面圖:
ggplot(mpg,aes(x = displ, y = hwy))+
geom_point()+
facet_wrap(~class, nrow = 2)
與使用圖形屬性相比京景,使用分面的優(yōu)勢(shì)和劣勢(shì)分別是什么?如果有一個(gè)更大的數(shù)據(jù)集骗奖,你將如何權(quán)衡這兩種方法的優(yōu)劣确徙?
優(yōu)勢(shì):分類變量用分面屬性可以更好的查看不同分類內(nèi)數(shù)據(jù)之間的關(guān)系(xy之間的關(guān)系)
劣勢(shì):連續(xù)型變量用分面沒必要,麻煩還沒意義执桌。
五鄙皇、閱讀?facet_wrap 的幫助頁面。nrow 和ncol 的功能分別是什么仰挣?還有哪些選項(xiàng)可以控制分面的布局伴逸?為什么函數(shù)facet_grid() 沒有變量nrow 和ncol ?
nrow代表分面的行數(shù)膘壶,ncol代表分面的列數(shù)错蝴≈薹撸控制布局的選項(xiàng)可以自己看下幫助文檔。
此處引用下語雀:Yq潛顷锰,這位老哥的解釋柬赐,感覺很好。
網(wǎng)格型(facet_grid) 和封裝型(facet_wrap) 官紫。網(wǎng)格分面生成的是一個(gè) 2 維的面板網(wǎng)格躺率, 面板的行與列通過變量來定義,封裝分面則先生成一個(gè) 1 維的面板條塊万矾,然后再封裝到 2 維中悼吱。(ggplot2 一書P(141) )可以看出 facet_grid() 本來就是一個(gè)二維的,故才會(huì)沒有變量 nrow 和 ncol良狈。
p1 <- ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_grid(drv ~ cyl)
p2 <- ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_wrap(drv ~ cyl)
p1+p2
左側(cè)為facet_grid(drv ~ cyl)后添,右側(cè)為facet_wrap(drv ~ cyl)大家對(duì)比下就明白了。
六薪丁、在使用函數(shù)facet_grid() 時(shí)遇西,一般應(yīng)該將具有更多唯一值的變量放在列上。為什么這么做呢严嗜?
共用一個(gè)縱坐標(biāo)粱檀,方便做互相間數(shù)據(jù)比較。
1.5 幾何對(duì)象
局部映射>全局映射
練習(xí):
一漫玄、在繪制折線圖茄蚯、箱線圖、直方圖和分區(qū)圖(對(duì)照英文睦优, 我覺得這里應(yīng)該是面積圖)時(shí)渗常,應(yīng)該分別使用哪種幾何對(duì)象?
折線圖:geom_line()
箱式圖:geom_boxplot()
直方圖:geom_histogram()
分區(qū)圖:geom_area()
二汗盘、在腦海中運(yùn)行以下代碼皱碘,并預(yù)測(cè)會(huì)有何種輸出。接著在R 中運(yùn)行代碼隐孽,并檢查你的預(yù)測(cè)是否正確癌椿。
ggplot(
data = mpg,
mapping = aes(x = displ, y = hwy, color = drv)
) +
geom_point() + # 幾何對(duì)象散點(diǎn)圖
geom_smooth(se = FALSE) # 幾何對(duì)象平滑數(shù)據(jù),擬合曲線菱阵,不加置信區(qū)間
三踢俄、show.legend = FALSE 的作用是什么?刪除它會(huì)發(fā)生什么情況送粱?你覺得我為什么要在本章前面的示例中使用這句代碼?
不加圖注褪贵,刪了就加上圖注了默認(rèn)出現(xiàn)在右側(cè)。圖太多冗余。
四脆丁、geom_smooth() 函數(shù)中的se 參數(shù)的作用是什么世舰?
不添加曲線的置信區(qū)間
五、以下代碼生成的兩張圖有什么區(qū)別嗎槽卫?為什么跟压?
p1 <- ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point() +
geom_smooth()
p2 <- ggplot() +
geom_point(
data = mpg,
mapping = aes(x = displ, y = hwy)
) +
geom_smooth(
data = mpg,
mapping = aes(x = displ, y = hwy)
)
p1 + p2
沒區(qū)別,映射一樣歼培,所以可以一起放到全局映射中震蒋。
六、 自己編寫R 代碼來生成以下各圖躲庄。
p1 <- ggplot(data = mpg, mapping = aes(x = displ, y = hwy))+
geom_point(size = 5)+
geom_smooth(se = FALSE,size = 2)
p2 <- ggplot(data = mpg, mapping = aes(x = displ, y = hwy))+
geom_point(size = 5)+
geom_smooth(mapping = aes(group = drv),se = FALSE,size = 2)
p3 <- ggplot(data = mpg, mapping = aes(x = displ, y = hwy, color = drv))+
geom_point(size = 5)+
geom_smooth(se = FALSE,size = 2)
p4 <- ggplot(data = mpg, mapping = aes(x = displ, y = hwy))+
geom_point(mapping = aes(color = drv),size = 5)+
geom_smooth(se = FALSE,size = 2)
p5 <- ggplot(data = mpg, mapping = aes(x = displ, y = hwy))+
geom_point(mapping = aes(color = drv),size = 5)+
geom_smooth(mapping = aes(linetype = drv),se = FALSE,size = 2)
#stroke參數(shù)的意思是描邊寬度查剖,shape為點(diǎn)的類型,此處color跟在stroke后面所以代表描邊顏色
p6 <- ggplot(data = mpg, mapping = aes(x = displ, y = hwy))+
geom_point(shape = 21, stroke = 3, color = 'white')+
geom_point(mapping = aes(color = drv),size = 3)
(p1+p2)/(p3+p4)/(p5+p6)
1.7 統(tǒng)計(jì)變換
diamonds數(shù)據(jù)集
名稱 | 含義 |
---|---|
price | price in US dollars($326-$18823)價(jià)格 |
carat | weight of the diamond (0.2–5.01)重量:克拉 |
cut | quality of the cut (Fair, Good, Very Good, Premium, Ideal)切割的質(zhì)量 |
color | diamond colour, from D (best) to J (worst)鉆石的成色D-J:最好-最差 |
clarity | a measurement of how clear the diamond is (I1 (worst), SI2, SI1, VS2, VS1, VVS2, VVS1, IF (best))鉆石的清晰度 |
x | length in mm (0–10.74)長(zhǎng) |
y | width in mm (0–58.9)寬 |
z | depth in mm (0–31.8)深度 |
depth | total depth percentage = z / mean(x, y) = 2 * z / (x + y) (43–79)總深度百分比 |
table | width of top of diamond relative to widest point (43–95)鉆石頂部相對(duì)最寬點(diǎn)的寬度 |
練習(xí):
一噪窘、stat_summary()函數(shù)的默認(rèn)幾何對(duì)象是什么笋庄?不使用統(tǒng)計(jì)變換函數(shù)的話,如何使用幾何對(duì)象函數(shù)重新生成以上的圖倔监?
# 使用統(tǒng)計(jì)函數(shù)stat_summary來繪圖直砂,它的默認(rèn)幾何對(duì)象是geom_pointrange
ggplot(diamonds)+
stat_summary(aes(x = cut, y = depth),
fun.max = max,
fun.min = min,
fun = median)
# 下面使用geom_pointrange進(jìn)行繪圖
ggplot(diamonds)+
geom_pointrange(aes(x = cut, y = depth),
stat = 'summary', #統(tǒng)計(jì)變換改為summary,默認(rèn)的idendity是不做處理
fun.max = max, #最大值
fun.min = min, #最小值
fun = median) #中位數(shù)
二浩习、geom_col()函數(shù)的功能是什么静暂?它和geom_bar()函數(shù)有何不同?
# 看geom_col()幫助文檔原文是這么寫的:If you want the heights of the bars to represent # values in the data, use geom_col() instead. geom_bar() uses stat_count() by default: # it counts the number of cases at each x position. geom_col() uses stat_identity(): # it leaves the data as is.
# 左圖
p1 = ggplot(diamonds)+
geom_bar(aes(x = cut))
# 右圖
p2 = ggplot(diamonds)+
geom_col(aes(x = cut, y = depth))
library(patchwork)
p1|p2
聯(lián)系:兩個(gè)函數(shù)都是用來做柱狀圖的谱秽。geom_col()的條柱高度可以代表數(shù)據(jù)集中某個(gè)變量的數(shù)值(即默認(rèn)統(tǒng)計(jì)變換是stat_identity()); geom_bar()的條柱高度只能代表x軸每個(gè)位置的例數(shù)(即默認(rèn)統(tǒng)計(jì)變換是stat_count())洽蛀。
三、多數(shù)幾何對(duì)象和統(tǒng)計(jì)變換都是成對(duì)出現(xiàn)的弯院,總是配合使用辱士。仔細(xì)閱讀文檔,列出所有成對(duì)的幾何對(duì)象和統(tǒng)計(jì)變換听绳。它們有什么共同之處?
太多了沒列
四异赫、stat_smooth() 函數(shù)會(huì)計(jì)算出什么變量椅挣?哪些參數(shù)可以控制它的行為?
查閱stat_smooth()的幫助文檔(?stat_smooth())可以看到有一項(xiàng)(Computed variables)
所以該函數(shù)回計(jì)算出的變量為:
- y predicted value(預(yù)測(cè)值)
- ymin lower pointwise confidence interval around the mean(均值附近的下點(diǎn)置信區(qū)間)
- ymax upper pointwise confidence interval around the mean(均值附近的上點(diǎn)置信區(qū)間)
- se standard error(標(biāo)準(zhǔn)誤差)
可以控制它的行為的參數(shù):
- position 調(diào)整位置
- method smooth的方法或函數(shù)如:"lm", "glm", "gam", "loess" or a function(自定義函數(shù))
- formula 在平滑函數(shù)中用的公式如:y ~ x, y ~ poly(x, 2), y ~ log(x). NULL by default, in which case method = NULL implies formula = y ~ x when there are fewer than 1,000 observations and formula = y ~ s(x, bs = "cs") otherwise.
- se 是否顯示標(biāo)準(zhǔn)差
- ...
五塔拳、在比例條形圖中鼠证,我們需要設(shè)定 group = 1,這是為什么呢靠抑?換句話說量九,以下兩張圖會(huì)有什么問題?
p1 <- ggplot(data = diamonds) +
geom_bar(mapping = aes(x = cut, y = after_stat(prop)))
p2 <- ggplot(data = diamonds) +
geom_bar(mapping = aes(x = cut, fill = color, y = after_stat(prop)))
library(pacthwork)
p1|p2
我們發(fā)現(xiàn)不加group=1這樣系統(tǒng)回默認(rèn)x軸每一個(gè)值都是1
p1 <- ggplot(data = diamonds) +
geom_bar(mapping = aes(x = cut, y = after_stat(prop),group = 1))
p2 <- ggplot(data = diamonds) +
geom_bar(mapping = aes(x = cut, fill = color, y = after_stat(prop),group = color))
p1|p2
p1加上group=1意思就是x軸所有值是1組,然后計(jì)算不同值(fair荠列、good等)在這個(gè)組里占的比例
p2為什么不加group=1反而是加group=color吶类浪?因?yàn)槲覀兌嗔艘粋€(gè)參數(shù)fill = color,所以我們圖中的條帶數(shù)是cutcolor即5×7=35個(gè)肌似,所以x軸所有值有35個(gè)組费就。所以計(jì)算百分比應(yīng)該是計(jì)算35個(gè)組的百分比,所以就是以顏色來計(jì)算百分比川队,即每組所有顏色的寬度相加代表這個(gè)組的值力细,然后除以所有組的所有顏色寬度相加的值。*
1.8 位置調(diào)整
所有圖層均具有位置調(diào)整共來解決重疊的幾何圖形固额。通過使用geom或stat函數(shù)的position參數(shù)來覆蓋默認(rèn)值眠蚂。
- position = "identity" 將每個(gè)對(duì)象值直接顯示再圖中,這樣數(shù)據(jù)會(huì)有重疊斗躏,不適合展示結(jié)果
- position = "fill" 堆疊條形圖每組條形圖具有相同的高度河狐,這樣可以輕松比較各組間比例。(即堆疊百分比條形圖)
- position = "dodge" 并列條形圖
- position = "stack" 堆疊條形圖(堆疊的是具體數(shù)值)
- position = "jitter" 數(shù)據(jù)隨機(jī)抖動(dòng)(一般用于散點(diǎn)圖瑟捣,可以避免點(diǎn)的重合)
if(!require("ggplot2"))install.packages("ggplot2")
if(!require("patchwork"))install.packages("patchwork")
library("ggplot2")
library("patchwork")
p0 <- ggplot(diamonds,aes(x= cut, fill = clarity))+
geom_bar()+
labs(title = "position_stack")
p1 <- ggplot(diamonds,aes(x= cut, fill = clarity))+
geom_bar(alpha = 0.2, position = "identity")+
labs(title = "position_identity")
# p1和p2修改位置參數(shù)的效果是一樣的馋艺,只是寫法不一樣。
p2 <- ggplot(diamonds,aes(x= cut, color = clarity))+
geom_bar(fill = NA, position = position_identity())+
labs(title = "position_identity")
p3 <- ggplot(diamonds, aes(x = cut, fill = clarity))+
geom_bar(position = "fill")+
labs(title = "position_fill")
p4 <- ggplot(diamonds, aes(x=cut, fill = clarity))+
geom_bar(position = position_dodge())+
labs(title = "position_dodge")
pt <- (p0|p1|p2)/(p3|p4)
ggsave("Rplot.png",pt)
- p0默認(rèn)位置參數(shù)為stack迈套,即直接原始數(shù)據(jù)堆疊
- p1修改位置參數(shù)為identity捐祠,但是這樣直接顯示原始數(shù)據(jù)(都從x軸底部開始),造成了數(shù)據(jù)重疊不利于分析桑李,所以使用了alpha參數(shù)踱蛀,讓圖形透明化。
- p2修改位置參數(shù)為identity贵白,這次采用直接將填充為無(即背景色)率拒,然后使用color參數(shù)給上線條顏色,這樣也可以看出來每組內(nèi)不同clarity的數(shù)量
- p3修改位置參數(shù)為fill禁荒,堆疊百分比條形圖猬膨,有利于對(duì)比不同組內(nèi)clarity的比例。
- p4修改位置參數(shù)為dodge呛伴,將每組條形依次并列放置勃痴,有利于輕松比較每個(gè)條形的數(shù)值。
回憶上一節(jié)繪制的mpg的displ和hwy的散點(diǎn)圖會(huì)發(fā)現(xiàn)圖中的點(diǎn)數(shù)是126個(gè)热康,但是數(shù)據(jù)集中有234個(gè)觀測(cè)值
通過位置調(diào)整方式改為抖動(dòng)即:“jitter”為每個(gè)數(shù)據(jù)點(diǎn)添加一個(gè)很小的隨機(jī)抖動(dòng)沛申,可以讓重疊的點(diǎn)分散開。因?yàn)椴僮骱苡杏每梢宰屛覀兛吹秸嬲臄?shù)據(jù)的聚集模式姐军,所以ggplot2提供了一個(gè)geom_jitter()函數(shù)
ggplot(mpg,aes(displ, hwy))+
geom_point(position = position_jitter())
練習(xí):
一铁材、下圖有什么問題尖淘?怎么改善?
ggplot(data = mpg, mapping = aes(x = cty, y = hwy)) +
geom_point()
點(diǎn)位重疊了著觉,調(diào)整位置位jitter
ggplot(data = mpg, mapping = aes(x = cty, y = hwy)) +
geom_jitter()
二村生、geom_jitter() 使用哪些參數(shù)來控制抖動(dòng)的程度?
width和height
使用?geom_jitter()查看幫助文檔固惯,原文的解釋是:Amount of vertical and horizontal jitter. The jitter is added in both positive and negative directions, so the total spread is twice the value specified here.即正負(fù)方向都加了抖動(dòng)值梆造,默認(rèn)是40%,所以實(shí)際抖動(dòng)是0.8葬毫。觀察下圖
p1 <- ggplot(data = mpg, mapping = aes(x = cty, y = hwy)) +
geom_jitter()
p2 <- ggplot(data = mpg, mapping = aes(x = cty, y = hwy)) +
geom_jitter(width = 0.2,
height = 0.2)
p1+p2
三镇辉、對(duì)比geom_jitter() 與geom_count()。
p1 <- ggplot(data = mpg, mapping = aes(x = cty, y = hwy)) +
geom_jitter()
p2 <- ggplot(data = mpg, mapping = aes(x = cty, y = hwy)) +
geom_count()
p1+p2
對(duì)比圖形可間贴捡,jitter為添加抖動(dòng)忽肛,count為對(duì)重疊點(diǎn)進(jìn)行重新計(jì)數(shù)并根據(jù)計(jì)數(shù)多少改變點(diǎn)的大小。
四烂斋、geom_boxplot() 函數(shù)的默認(rèn)位置調(diào)整方式是什么屹逛?創(chuàng)建 mpg 數(shù)據(jù)集的可視化表示來演示一下。
?geom_boxplot查看默認(rèn)位置調(diào)整方式是dodge2
ggplot(mpg,aes(x = drv, y = cty))+
geom_boxplot()
1.9 坐標(biāo)系
默認(rèn)坐標(biāo)系是笛卡爾直角坐標(biāo)系汛骂。
1罕模、coord_flip可以交換x和y軸,這在你想把箱線圖水平過來帘瞭,或者x軸組名太長(zhǎng)擠不開的時(shí)候很好用
p1 <- ggplot(mpg,aes(x= class, y = hwy))+
geom_boxplot()
p2 <- ggplot(mpg,aes(x= class, y = hwy))+
geom_boxplot()+
coord_flip()
p1+p2
2淑掌、coord_polar()函數(shù)使用極坐標(biāo)系。
p0 <- ggplot(diamonds,aes(x = cut, fill = cut))+
geom_bar(width = 1)+ #將條帶寬度設(shè)置為1蝶念,默認(rèn)值是圖形分辨率的90%
theme(aspect.ratio = 1)+ #參數(shù)aspect.ratio表示圖形的縱橫比我們?cè)O(shè)置為1
labs(x = NULL, y = NULL) #不顯示x抛腕、y軸的標(biāo)注即(cut和count字符)
p1 <- p0+coord_flip()
p2 <- p0+coord_polar()
p1+p2
練習(xí):
一、使用coord_polar() 函數(shù)將堆疊式條形圖轉(zhuǎn)換為餅圖媒殉。
p0 <- ggplot(diamonds,aes(x= cut, fill = clarity))+
geom_bar(width = 1)+
labs(x=NULL, y = NULL)+
theme(aspect.ratio = 1)
p1 <- p0+coord_polar()
p2 <- p0+coord_polar(theta = "y")
p0+p1+p2
對(duì)比兩圖差異担敌,參數(shù)theta介紹:variable to map angle to (x or y),意思是:以哪個(gè)變量值映射到角度廷蓉,默認(rèn)值是x全封,所以中間圖p1是五等分角度(因?yàn)閤軸式cut,5個(gè)cut就5等分)苦酱。右邊圖改為了theta = "y"(即根據(jù)每個(gè)組計(jì)算的count數(shù)來映射到角度)
換一個(gè)餅圖售貌,我們把p0的位置參數(shù)改為fill即條帶按百分比堆疊。這樣畫出來的餅圖沒有空白疫萤,因?yàn)槊總€(gè)組自己是1
p0 <- ggplot(diamonds,aes(x= cut, fill = clarity))+
geom_bar(width = 1, position = "fill")+
labs(x=NULL, y = NULL)+
theme(aspect.ratio = 1)
p1 <- p0+coord_polar()
p2 <- p0+coord_polar(theta = "y")
p0+p1+p2
二、labs() 函數(shù)的功能是什么敢伸?閱讀一下文檔扯饶。
?labs()閱讀幫助文檔,運(yùn)行下示例代碼就可以知道。
內(nèi)置參數(shù)給圖形修改各種名字尾序,如:標(biāo)題钓丰,子標(biāo)題,右下角標(biāo)注每币,給圖形加字母標(biāo)注携丁,修改xy軸名字等。
三兰怠、coord_quickmap() 函數(shù)和 coord_map() 函數(shù)的區(qū)別是什么梦鉴?
畫地圖用的,感覺自己應(yīng)該用不要揭保,所以沒看肥橙,需要了再學(xué)吧。
四秸侣、下圖表明城市和公路燃油效率之間有什么關(guān)系存筏?為什么 coord_fixed() 函數(shù)很重要?geom_abline() 函數(shù)的作用是什么味榛?
p1 <- ggplot(data = mpg, mapping = aes(x = cty, y = hwy)) +
geom_point() +
geom_abline() +
coord_fixed()
p2 <- ggplot(data = mpg, mapping = aes(x = cty, y = hwy)) +
geom_point() +
geom_abline()
p1+p2
?coord_fixed()第一參數(shù)ratio:aspect ratio, expressed as y / x椭坚。即y軸與x軸的比例。默認(rèn)是1搏色,自己繪圖的時(shí)候?yàn)榱耸箶?shù)據(jù)展現(xiàn)效果更美觀時(shí)善茎,可以對(duì)xy軸的比例進(jìn)行一定的調(diào)整。其他參數(shù)自己看下幫助文檔继榆,很簡(jiǎn)單巾表。
?geom_abline()查看幫助文檔,運(yùn)行示例代碼略吨。作用:添加一條參考線集币,可以用來比較數(shù)據(jù)差別怎么樣。注意他不是擬合數(shù)據(jù)為一條趨勢(shì)線翠忠。下圖是geom_abline()和geom_smooth()區(qū)別
p1 <- ggplot(data = mpg, mapping = aes(x = cty, y = hwy)) +
geom_point() +
geom_abline()+
coord_fixed()
p2 <- ggplot(data = mpg, mapping = aes(x = cty, y = hwy)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE)+
coord_fixed()
p1+p2
1.10 圖形分層語法
ggplot2繪制圖形的基本框架:
ggplot(data = <DATA>) +
<GEOM_FUNCTION>(
mapping = aes(<MAPPINGS>),
stat = <STAT>,
position = <POSITION>
) +
<COORDINATE_FUNCTION> +
<FACET_FUNCTION>
7個(gè)參數(shù)即<>內(nèi)的內(nèi)容:數(shù)據(jù)集鞠苟、幾何對(duì)象、映射集合秽之、統(tǒng)計(jì)變換当娱、位置調(diào)整、坐標(biāo)系和分面模式考榨。大部分情況下不需要全部提供跨细,因?yàn)镽提供了很多默認(rèn)值。
最后河质,大家明白ggplot2的繪圖原理即可冀惭,以后遇到什么圖震叙,查看幫助文檔+Google就行,網(wǎng)上有很多大神寫的代碼~
部分參考:
https://www.yuque.com/erhuoqian/mudww7/ugt8l6#U7UV9
https://ggplot2.tidyverse.org/reference/
這個(gè)是R數(shù)據(jù)科學(xué)英文版的電子書散休,大家感興趣可以看下:https://r4ds.had.co.nz/