R數(shù)據(jù)科學(xué)(一)ggplot2

1. install packages

install.packages("tidyverse")
library(tidyverse)
tidyverse_update()
##################

安裝三個數(shù)據(jù)包

install.packages(c("nycflights13", "gapminder", "Lahman"))

tidyverse 包括ggplot2, tibble, tidyr, readr, purrr和 dplyr包

PART I Explore

CHAPTER 1: Data Visualization with ggplot2

以ggplot2包中的mpg數(shù)據(jù)為例,它是一個數(shù)據(jù)框,每行為一個數(shù)據(jù),每列為一個觀測。mpg包括38種車的數(shù)據(jù)。

# 查看該數(shù)據(jù)集
head(ggplot2::mpg)

displ:車發(fā)動機(jī)大小,hwy:車的燃油效率

  • 用該數(shù)據(jù)集創(chuàng)造第一幅ggplot圖
library(ggplot2)
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy))

該圖表示發(fā)動機(jī)大小與燃油呈現(xiàn)負(fù)相關(guān)。

  • ggplot() 函數(shù)產(chǎn)生最基礎(chǔ)的坐標(biāo)系統(tǒng),然后可以在上面加圖層,
# 空圖層,背景,顏色,字體都設(shè)好了
ggplot(data = mpg)  
# aes()將數(shù)字映射為圖形
ggplot(data = mpg) + geom_point(aes(displ,hwy)) 

#查看mpg數(shù)據(jù)
dim(mpg)
head(mpg)
# 查看hwy和cyl的關(guān)系
ggplot(mpg,aes(hwy,cyl)) + geom_point()

這里提供了一個畫圖模板:
ggplot(data = <DATA>) +
<GEOM_FUNCTION>(mapping = aes(<MAPPINGS>))

Aesthetic Mappings

aesthetic美學(xué)的,在圖中表示點的大小,顏色等
我們可以把點的顏色按某個數(shù)值分組,如class

ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy, color = class))

也可以按點的大小分組

ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy, size = class))

或者映射給透明度或者形狀

# Top
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy, alpha = class))
# Bottom
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy, shape = class))
# ggplot一次只能用6個形狀,這里有7個,所以SUV不顯示了

我們可以手動定義幾何類型

ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy), color = "blue")

練習(xí)題:
1.為什么點不是藍(lán)色的?

ggplot(data = mpg) +
geom_point(
mapping = aes(x = displ, y = hwy, color = "blue")
)

因為color放在映射里面了,映射自動從彩色里賦值。

ggplot(data = mpg) +
geom_point(
mapping = aes(x = displ, y =hwy, color = cty))

2.注意映射連續(xù)變量與分類變量的區(qū)別。如顏色連續(xù)變量為一個顏色從深到淺,分類變量為各個顏色的分類。

ggplot(data = mpg) +
geom_point(
mapping = aes(x = displ, y =hwy, color = displ))

4.一個變量有多個映射是可以的,但是造成了信息的冗余,一般不會這樣做。

  1. stroke是映射什么的?
ggplot(mtcars, aes(wt, mpg)) +
  geom_point(shape = 21, colour = "black", fill = "white", size = 5, stroke = 1)

stroke映射點的邊框粗細(xì)。

ggplot(mpg, aes(x = displ, y = hwy, colour = displ < 5)) +
  geom_point()

注意:R語法很容易出錯,注意(),“”是否配對,如果運(yùn)行R代碼無反應(yīng),按Esc鍵退出。

Facets 分面

增加信息的方式一個是將變量給映射,另外一個方法是將分類變量給分面,從而將圖分成幾個小的面。
分面有兩種函數(shù),facet_wrap(~分類變量,nrow,ncol)這個函數(shù)放入一個分類變量。

ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_wrap(~ class, nrow = 2)

facet_grid(a ~ b) 可以用兩個組合變量來分面

ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_grid(drv ~ cyl)

facet_grid()函數(shù)如果只想用一個變量來分面,可以用.留空。

ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_grid(. ~ cyl)
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_grid(drv ~ .)

練習(xí)題:

  1. 如果用連續(xù)型變量來分面會出現(xiàn)什么后果?
head(mpg)
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_wrap(~ cty, nrow = 2)

結(jié)果是將連續(xù)型變量轉(zhuǎn)換為因子,每個因子都有一個分面。
2.該圖中有空位子,表示什么意思?

ggplot(data = mpg) +
geom_point(mapping = aes(x = drv, y = cyl))

空點表示該位子無數(shù)值。
3.下面兩個代碼有何不同?

ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_grid(drv ~ .)
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_grid(. ~ cyl)

.的位置代表不想用該變量進(jìn)行分面。
4.用分面代替顏色映射的優(yōu)勢和劣勢是什么?
一幅圖中人眼可以識別的顏色不超過9種,分面可以區(qū)分更多的信息,但是不容易相互比較。

3.6 Geometric Objects 幾何對象

幾何對象是把數(shù)據(jù)用圖形的方式映射出來

# left
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy))
# right
ggplot(data = mpg) +
geom_smooth(mapping = aes(x = displ, y = hwy))

每個幾何對象函數(shù)都有對應(yīng)的映射參數(shù),但是具有獨(dú)立性,有些不能通用

ggplot(data = mpg) +
geom_smooth(mapping = aes(x = displ, y = hwy, linetype = drv))

許多幾何對象可以展示多組圖形,ggplot2會自動分組,但是不展示圖例。

ggplot(data = mpg) +
geom_smooth(mapping = aes(x = displ, y = hwy))
ggplot(data = mpg) +
geom_smooth(mapping = aes(x = displ, y = hwy, group = drv))
ggplot(data = mpg) +
geom_smooth(
mapping = aes(x = displ, y = hwy, color = drv),
show.legend = FALSE
)

ggplot2也可以展示多個圖層

ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
geom_smooth(mapping = aes(x = displ, y = hwy))

同一張圖顯示多個幾何對象--局部映射和全局映射的區(qū)別,如有沖突,以局部變量為準(zhǔn)。

# ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
# geom_point(mapping = aes(color = class)) +
# geom_smooth(
# data = filter(mpg, class == "subcompact"),
# se = FALSE
# )

filter設(shè)置geom_smooth幾何對象的過濾,se表示標(biāo)準(zhǔn)差
練習(xí)題:
Exercise 3.6.2 該代碼畫圖是什么樣的?

ggplot(data = mpg, mapping = aes(x = displ, y = hwy, colour = drv)) +
  geom_point() +
  geom_smooth(se = FALSE)

color作為全局變量傳遞給point和smooth,因此,這兩個都畫出來了。

Exercise 3.6.3
What does show.legend = FALSE do? What happens if you remove it? Why do you think I used it earlier in the chapter?

ggplot(data = mpg) +
  geom_smooth(
    mapping = aes(x = displ, y = hwy, colour = drv),
  )

ggplot(data = mpg) +
  geom_smooth(
    mapping = aes(x = displ, y = hwy, colour = drv),
    show.legend = FALSE)
  1. Re-create the R code necessary to generate the following graphs.
ggplot(mpg,aes(displ,hwy))+geom_point()+geom_smooth(se=F)
ggplot(mpg,aes(displ,hwy))+geom_point()+geom_smooth(aes(group=drv),se=F)
ggplot(mpg, aes(x = displ, y = hwy, colour = drv)) +
  geom_point() +
  geom_smooth(se = FALSE)
ggplot(mpg,aes(displ,hwy))+geom_point(aes(color=drv))+geom_smooth(se=F)
ggplot(mpg,aes(displ,hwy))+geom_point(aes(color=drv))+geom_smooth(aes(linetype=drv),se=F)
ggplot(mpg, aes(x = displ, y = hwy)) +
   geom_point(size = 4, color = "white") +
   geom_point(aes(colour = drv))

3.7 Statistical Transformations 統(tǒng)計變換

統(tǒng)計變換:繪圖時用來計算新數(shù)據(jù)的算法叫做統(tǒng)計變換stat
每個幾何對象函數(shù)都有一個默認(rèn)的統(tǒng)計變換,每個統(tǒng)計變換函數(shù)都又一個默認(rèn)的幾何對象。
用幾何對象函數(shù)geom_bar作直方圖,默認(rèn)統(tǒng)計變換是stat_count.
一般可以用默認(rèn)的統(tǒng)計變換,以下情況要用新的統(tǒng)計變換:
1.覆蓋默認(rèn)的統(tǒng)計變換

  • 直方圖默認(rèn)的統(tǒng)計變換是stat_count,也就是統(tǒng)計計數(shù)。當(dāng)需要直接用原表格的數(shù)據(jù)作圖時就會需要覆蓋默認(rèn)的。
library(tibble)

demo <- tribble(
~a, ~b,
"bar_1", 20,
"bar_2", 30,
"bar_3", 40
)
# 默認(rèn)stat=count,這里改成 "identity"

ggplot(data = demo) +
geom_bar(
mapping = aes(x = a, y = b), stat = "identity"
)

2.覆蓋從統(tǒng)計變換生成變量到圖形屬性的默認(rèn)映射
直方圖默認(rèn)的y軸是x軸的計數(shù)。此例子中x軸是五種cut(切割質(zhì)量),直方圖自動統(tǒng)計了這五種質(zhì)量的鉆石的統(tǒng)計計數(shù),當(dāng)你不想使用計數(shù),而是想顯示各質(zhì)量等級所占比例的時候就需要用到prop。

ggplot(diamonds,aes(cut,..prop..,group=1))+geom_bar()
#group=1的意思是把所有鉆石作為一個整體,顯示五種質(zhì)量的鉆石所占比例體現(xiàn)出來。

3.在代碼中強(qiáng)調(diào)統(tǒng)計變換
以stat_summary為例。

ggplot(diamonds)+stat_summary(aes(cut,depth),
                              fun.ymin = min,
                              fun.ymax=max,
                              fun.y=median)

練習(xí)題:
1.stat_summary()默認(rèn)的幾何對象是什么?
stat_summary的默認(rèn)幾何圖形是geom_pointrange,而geom_pointrange默認(rèn)的統(tǒng)計變換卻是identity

ggplot(diamonds) + geom_pointrange(aes(cut,depth),
                                   stat = 'summary',
                                   fun.ymin=min,
                                   fun.ymax=max,
                                   fun.y=median)
  1. geom_col()與geom_bar()的區(qū)別
    geom_col()的默認(rèn)統(tǒng)計變換為identity(),geom_bar()默認(rèn)為count()

  2. stat_smooth()計算變量為預(yù)測值,最低和最高置信區(qū)間及SE

  3. geom_bar(aes(y = ..prop..))中g(shù)roup=1的設(shè)置?
    默認(rèn)分組是等于x的,分組是在組內(nèi)執(zhí)行

ggplot(data = diamonds) +
geom_bar(mapping = aes(x = cut, y = ..prop..))
ggplot(data = diamonds) +
geom_bar(
mapping = aes(x = cut, fill = color, y = ..prop..)
)
ggplot(data = diamonds) +
  geom_bar(mapping = aes(x = cut, y = ..prop.., group = 1))

ggplot(data = diamonds) +
  geom_bar(mapping = aes(x = cut, fill = color, y = ..prop.., group = color))

3.8 Position Adjustments

geom_bar的顏色可以用color和fill調(diào)整

ggplot(data = diamonds) +
geom_bar(mapping = aes(x = cut, color = cut))
ggplot(data = diamonds) +
geom_bar(mapping = aes(x = cut, fill = cut))

ggplot(data = diamonds) +
geom_bar(mapping = aes(x = cut, fill = clarity))

bar的位置有三個參數(shù)可以調(diào)整"identity", "dodge" or "fill"
"identity"直接顯示

ggplot(diamonds,aes(cut,fill=clarity))+geom_bar(alpha=1/5,position = 'identity')
ggplot(diamonds,aes(cut,color=clarity))+geom_bar(fill=NA,position = 'identity')

"fill"堆疊式,x每個分組都為100%

ggplot(data = diamonds) +
geom_bar(
mapping = aes(x = cut, fill = clarity),
position = "fill"
)

"dodge" 并列式,一個放在另一個旁邊

ggplot(data = diamonds) +
geom_bar(
mapping = aes(x = cut, fill = clarity),
position = "dodge"
)

position = "jitter" 添加點的隨機(jī)擾動,使重復(fù)的點暴露出來。

ggplot(data = mpg) +
geom_point(
mapping = aes(x = displ, y = hwy),
position = "jitter"
)

?position_dodge, ?position_fill, ?position_identity, ?position_jitter, and ?posi
tion_stack.

ggplot(mtcars,aes(factor(cyl),fill=factor(vs))) + 
  geom_bar(position = position_dodge(preserve = 'total'))

練習(xí)題:

  1. geom_jitter()哪個參數(shù)控制擾動大???
    width,height從水平和垂直方向控制

3.對比geom_jitter() 和 geom_count()

#geom_jitter()對點添加隨機(jī)擾動
ggplot(data = mpg, mapping = aes(x = cty, y = hwy)) +
  geom_jitter()
#geom_count()重復(fù)的點越多,點越大
ggplot(data = mpg, mapping = aes(x = cty, y = hwy)) +
  geom_count()
  1. geom_boxplot()默認(rèn)的統(tǒng)計變換是什么?
ggplot(data = mpg, mapping = aes(x = drv, y = hwy,color=class)) +
  geom_boxplot()
ggplot(data = mpg, aes(x = drv, y = hwy, colour = class)) +
  geom_boxplot(position = "identity")

默認(rèn)為position_dodge()

3.9 Coordinate Systems 坐標(biāo)系統(tǒng)

ggplot2默認(rèn)為笛卡爾坐標(biāo)系,x和y軸是獨(dú)立的
coord_flip() 調(diào)換x和y軸

ggplot(data = mpg, mapping = aes(x = class, y = hwy)) +
geom_boxplot()
ggplot(data = mpg, mapping = aes(x = class, y = hwy)) +
geom_boxplot() +
coord_flip()

coord_quickmap
為地圖設(shè)置長寬比
此處需要加載maps包,否則會報錯。

library(maps)
#如果報錯則:install.packages("maps")
#library(maps)
nz <- map_data("nz")
 
ggplot(nz, aes(long, lat, group = group)) +
  geom_polygon(fill = "white", colour = "black")
 # geom_polygon 是多邊形圖
ggplot(nz, aes(long, lat, group = group)) +
  geom_polygon(fill = "white", colour = "black") +
  coord_quickmap()

coord_polar()極坐標(biāo)系統(tǒng)

bar <- ggplot(data = diamonds) +
geom_bar(
mapping = aes(x = cut, fill = cut),
show.legend = FALSE,
width = 1
) +
theme(aspect.ratio = 1) +
labs(x = NULL, y = NULL)
bar + coord_flip()
bar + coord_polar()

#width = 1把柱形圖中間的空去掉了,
ggplot(mpg, aes(x = factor(1), fill = drv)) +
  geom_bar()
#theta = "y"是將角度按y軸變量來設(shè)置,如不設(shè)置,會出現(xiàn)中間空心原點
ggplot(mpg, aes(x = factor(1), fill = drv)) +
  geom_bar(width = 1) +
  coord_polar(theta = "y")
ggplot(mpg, aes(x = factor(1), fill = drv)) +
  geom_bar(width = 1) +
  coord_polar()
ggplot(diamonds) + geom_bar(aes(x=cut,fill=cut))+coord_polar()

#多組的bar圖也能畫出餅圖
head(diamonds)
ggplot(diamonds,aes(cut,fill=color)) + 
  geom_bar(position = "fill") #注意position位置參數(shù)的設(shè)置,默認(rèn)position = "identity"

ggplot(diamonds,aes(cut,fill=color)) + 
  geom_bar(position = "fill") + 
  coord_polar(theta = "y")

Exercise 3.9.2 lab()函數(shù)可以給圖層增加x和y的標(biāo)簽和title

ggplot(data = mpg, mapping = aes(x = class, y = hwy)) +
  geom_boxplot() +
  coord_flip() +
  labs(y = "Highway MPG", x = "", title = "Highway MPG by car class")

Exercise 3.9.4
coord_fixed()保持線為45度

p <- ggplot(data = mpg, mapping = aes(x = cty, y = hwy)) +
  geom_point() +
  geom_abline()
p
p + coord_fixed() 

3.10 The Layered Grammar of Graphics
ggplot2通用模板

ggplot(data = <DATA>) + #數(shù)據(jù)集data
<GEOM_FUNCTION>( #幾何對象geom
mapping = aes(<MAPPINGS>), #映射aes
stat = <STAT>, #統(tǒng)計變換stat
position = <POSITION> #位置調(diào)整position
) +
<COORDINATE_FUNCTION> + #坐標(biāo)系統(tǒng)
<FACET_FUNCTION> #分面系統(tǒng)

圖形構(gòu)建的過程由以上五個指標(biāo)構(gòu)建,后面兩個用于微調(diào)。

閱讀推薦:
生信技能樹公益視頻合輯:學(xué)習(xí)順序是linux,r,軟件安裝,geo,小技巧,ngs組學(xué)!
B站鏈接:https://m.bilibili.com/space/338686099
YouTube鏈接:https://m.youtube.com/channel/UC67sImqK7V8tSWHMG8azIVA/playlists
生信工程師入門最佳指南:https://mp.weixin.qq.com/s/vaX4ttaLIa19MefD86WfUA

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容