R數據科學(一)ggplot2

1. install packages

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

安裝三個數據包

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

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

PART I Explore

CHAPTER 1: Data Visualization with ggplot2

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

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

displ:車發動機大小,hwy:車的燃油效率

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

該圖表示發動機大小與燃油呈現負相關。

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

#查看mpg數據
dim(mpg)
head(mpg)
# 查看hwy和cyl的關系
ggplot(mpg,aes(hwy,cyl)) + geom_point()

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

Aesthetic Mappings

aesthetic美學的,在圖中表示點的大小,顏色等
我們可以把點的顏色按某個數值分組,如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")

練習題:
1.為什么點不是藍色的?

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.注意映射連續變量與分類變量的區別。如顏色連續變量為一個顏色從深到淺,分類變量為各個顏色的分類。

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映射點的邊框粗細。

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

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

Facets 分面

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

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()函數如果只想用一個變量來分面,可以用.留空。

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 ~ .)

練習題:

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

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

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

空點表示該位子無數值。
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)

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

3.6 Geometric Objects 幾何對象

幾何對象是把數據用圖形的方式映射出來

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

每個幾何對象函數都有對應的映射參數,但是具有獨立性,有些不能通用

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))

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

# 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設置geom_smooth幾何對象的過濾,se表示標準差
練習題:
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 統計變換

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

  • 直方圖默認的統計變換是stat_count,也就是統計計數。當需要直接用原表格的數據作圖時就會需要覆蓋默認的。
library(tibble)

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

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

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

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

3.在代碼中強調統計變換
以stat_summary為例。

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

練習題:
1.stat_summary()默認的幾何對象是什么?
stat_summary的默認幾何圖形是geom_pointrange,而geom_pointrange默認的統計變換卻是identity

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

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

  3. geom_bar(aes(y = ..prop..))中group=1的設置?
    默認分組是等于x的,分組是在組內執行

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調整

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的位置有三個參數可以調整"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" 添加點的隨機擾動,使重復的點暴露出來。

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'))

練習題:

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

3.對比geom_jitter() 和 geom_count()

#geom_jitter()對點添加隨機擾動
ggplot(data = mpg, mapping = aes(x = cty, y = hwy)) +
  geom_jitter()
#geom_count()重復的點越多,點越大
ggplot(data = mpg, mapping = aes(x = cty, y = hwy)) +
  geom_count()
  1. geom_boxplot()默認的統計變換是什么?
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")

默認為position_dodge()

3.9 Coordinate Systems 坐標系統

ggplot2默認為笛卡爾坐標系,x和y軸是獨立的
coord_flip() 調換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
為地圖設置長寬比
此處需要加載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()極坐標系統

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軸變量來設置,如不設置,會出現中間空心原點
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位置參數的設置,默認position = "identity"

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

Exercise 3.9.2 lab()函數可以給圖層增加x和y的標簽和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>) + #數據集data
<GEOM_FUNCTION>( #幾何對象geom
mapping = aes(<MAPPINGS>), #映射aes
stat = <STAT>, #統計變換stat
position = <POSITION> #位置調整position
) +
<COORDINATE_FUNCTION> + #坐標系統
<FACET_FUNCTION> #分面系統

圖形構建的過程由以上五個指標構建,后面兩個用于微調。

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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,786評論 6 534
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,656評論 3 419
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,697評論 0 379
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,098評論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,855評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,254評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,322評論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,473評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,014評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,833評論 3 355
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,016評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,568評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,273評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,680評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,946評論 1 288
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,730評論 3 393
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,006評論 2 374

推薦閱讀更多精彩內容