UCLA-(R Graphics: Intro to ggplot2)笔记
目錄
原文請見R Graphics: Introduction to ggplot2 (12) (ucla.edu)https://stats.oarc.ucla.edu/stat/data/intro_ggplot2_int/ggplot2_intro_interactive.html#(12)
由于CSDN有時候圖會看不見,本文將不放置圖片
圖形的語法元素
Sitka數據集(這一部分其實就是一個示范而已)
?ggplot()函數與aesthetics
Layers and overriding aesthetics
Aesthetics
?Mapping vs setting
Geoms
Geoms and aesthetics
Histograms
Density plots
Boxplots
Bar plots
Scatter plots
Line graphs
*Stats*
Scales
Scale functions for the axes
Modifying axis limits and titles
Guides visualize scales
Coordinate systems
Faceting (paneling)
Themes
?Specifying?theme()?arguments
?Changing the overall look with complete themes
Saving plots to files
From idea to final graphic: graphing the?Rabbit?data set {MASS}
The idea of the graph
Rabbit graph 1
Rabbit graph 2
Rabbit graph 3
Rabbit graph 4
Rabbit graph 5
Rabbit graph 6
Rabbit graph 7
Rabbit graph 8
Rabbit graph finished
原文請見R Graphics: Introduction to ggplot2 (12) (ucla.edu)https://stats.oarc.ucla.edu/stat/data/intro_ggplot2_int/ggplot2_intro_interactive.html#(12)
由于CSDN有時候圖會看不見,本文將不放置圖片
圖形的語法元素
1. Data:變量,可映射到圖的美學特征。
2. Geoms:圖形上的對象/形狀。
3. Stats: 匯總數據的統計轉換(例如 mean,confidence intervals(置信區間))
4. Scales: 圖形值(aesthetic values)到數據值的映射。圖例和軸可視化尺度
5. Coordinate systems(坐標系):數據被映射到圖形上的平面。
6. Faceting: 將數據分成子集,以創建同一圖形的多個變體(分面)。
Sitka數據集(這一部分其實就是一個示范而已)
為了練習使用圖形語法,我們將使用Sitka數據集(來自MASS包)。
注意:用包加載到R中的數據集可以立即使用。要在RStudio的Environment窗格中看到對象(所以你可以點擊查看它),在數據集上運行data(),然后在數據集上運行另一個函數,如str()。
> library(ggplot2) > library(MASS) > data() > str(Sitka)# 出現 'data.frame': 395 obs. of 4 variables:$ size : num 4.51 4.98 5.41 5.9 6.15 4.24 4.2 4.68 4.92 4.96 ...$ Time : num 152 174 201 227 258 152 174 201 227 258 ...$ tree : int 1 1 1 1 1 2 2 2 2 2 ...$ treat: Factor w/ 2 levels "control","ozone": 2 2 2 2 2 2 2 2 2 2 ...?ggplot()函數與aesthetics
所有圖形都以指定ggplot()函數開始(注意:不是包名ggplot2)
在ggplot()函數中,我們指定包含變量的數據集。這些變量將映射到aesthetics(圖的視覺屬性)。數據集必須是一個data.frame對象。
ggplot(data, aes(x=xvar, y=yvar))
data: 包含要繪制的變量的data.frame的名稱
x and y:?在圖形上放置對象的aesthetics(視覺位置吧應該是)
xvar and yvar:?映射到x和y的數據中的變量名
?注意aesthetics是在aes()中指定的,aes()本身嵌套在ggplot()中。
ggplot()內部指定的aesthetics被后續的層繼承:
# scatter plot of volume vs sales ggplot(txhousing, aes(x=volume, y=sales)) +geom_point()通過將Sitka數據集中的Time映射到x, size映射到y,初始化一個Time與size的關系圖。
如果沒有任何額外的層,就不會繪制數據。
意思就是:
ggplot(Sitka, aes(x=Time, y=size))只有這個不會生成圖,還需要像上面“+geom_point()”才會生成圖,否則只會生成坐標軸。
Layers and overriding aesthetics
單獨指定x和y的aesthetics將產生一個只有兩個軸的圖。
ggplot(data = txhousing, aes(x=volume, y=sales))我們將帶有字符+的圖層添加到圖形中,以添加圖形組件。
圖層由geoms,stats,scales和themes組成,我們將詳細討論這些內容。
請記住,每個后續層都從ggplot()繼承其aesthetics。但是,在一個層中指定新的aesthetics將覆蓋ggplot()中指定的aesthetics。
# scatter plot of volume vs sales # with rug plot colored by median sale price ggplot(txhousing, aes(x=volume, y=sales)) + # x=volume and y=sales inherited by all layers geom_point() +geom_rug(aes(color=median)) # color will only apply to the rug plot because not specified in ggplot() > library(ggplot2) > library(MASS) > ggplot(Sitka, aes(x=Time, y=size))+ + geom_point(aes(color=treat))+ + geom_smooth()上面兩個例子其實就是只要前面有加號就會后面的操作就會繼承ggplot()的aesthetics,就是在ggplot()所建立的坐標軸上繼續。注意:此處coloring僅應用于geom_point().
Aesthetics
aesthetcis是圖形中對象的視覺屬性。
哪些aesthetics是需要的,哪些aesthetics是允許的,這取決于geom。
經常被使用的aesthetics:
x:?沿著x軸定位
y:?沿著y軸定位
color: 對象的顏色;對于2D對象,是對象的輪廓(與下面的fill相比)
fill: 對象的填充色
linetype: 線條是如何畫出來的(實線、虛線、點線等)
shape:?散點圖中標記的形狀
size: 對象的大小
alpha:?對象的透明度(值介于0,即transparent和1,即opaque之間——將堆疊多少個對象變成不透明的倒數)
?Mapping vs setting
Map是在aes()函數內將aesthetics對應到變量。
# mapping color to median inside of aes() ggplot(txhousing, aes(x=volume, y=sales)) +geom_point(aes(color=median))Set是在aes()函數外將aesthetics對應到常量。
# setting color to green outside of aes() ggplot(txhousing, aes(x=volume, y=sales)) +geom_point(color="green")若果是在aes()函數內將aesthetics對應到常量會有意料之外的結果。
# color="green" inside of aes() # geom_point() cannot find a variable called "green" and # uses a default color instead ggplot(txhousing, aes(x=volume, y=sales)) +geom_point(aes(color="green")) # 雖為color但是可能為其它顏色Geoms
Geom函數在plot時產生的幾何形狀上有所不同。
常見的Geoms:
geom_bar():?以x軸為基的bar
geom_boxplot():?boxes-and-whiskers(不知道這是什么)
geom_errorbar():?T-shaped error bars
geom_density():?密度圖
geom_histogram(): 直方圖
geom_line(): lines
geom_point(): 散點圖
geom_ribbon():?bands spanning y-values across a range of x-values
geom_smooth():?smoothed conditional means (e.g.?loess smooth)(平滑條件均值)
geom_text(): text
Geoms and aesthetics
每個Geom需要aesthetics提供來定義。例如,geom_point()同時需要x和y,這是散點圖的最小規范。
Geoms接受aesthetics中的arguments而不同。例如:geom_point()接受aesthetic shape,但是geom_bar()不接受shape。
查看geom函數的幫助文件,可了解所需并理解asethetics。在geom的幫助文件的Asethetics部分中,所要求asethetics是加粗的。
我們來看看常見的geoms.
Histograms
ggplot(txhousing, aes(x=median)) + geom_histogram()直方圖是描述連續變量分布的常用選擇。
> ggplot(Sitka, aes(x=size))+ + geom_histogram(bins=20)bins默認為30,且bins不是aesthetic,所以不應該在aes()內。
Density plots
ggplot(txhousing, aes(x=median)) + geom_density()密度圖基本上是平滑的直方圖。
密度圖與直方圖不同,可以通過將分組變量映射到color來分組單獨繪制。
ggplot(txhousing, aes(x=median, color=factor(month))) + geom_density()Boxplots
ggplot(txhousing, aes(x=factor(year), y=median)) + geom_boxplot()箱線圖可以直觀地顯示分布的特定統計信息:
- lower and upper hinges of box: first and third quartiles
- middle line: median
- lower and upper whiskers:?(hinge?1.5×IQR)?and (hinge+1.5×IQR)?where?IQR?is the interquartile range (distance between hinges)
- dots: outliers
箱形圖對于比較組間連續變量的整體分布可能特別有用。
> ggplot(Sitka, aes(x=size, y=treat))+ + geom_boxplot()Bar plots
ggplot(diamonds, aes(x=cut)) + geom_bar()條形圖常用于顯示factor(categorical)變量的頻率。
> ggplot(Sitka, aes(x=treat))+ + geom_bar()填充條狀圖的顏色不是由aesthetic顏色控制的,而是由fill控制的,它只能映射到一個factor(catgorical)變量。我們可以通過將其中一個變量映射到geom_bar()中來可視化變量的交叉表:
ggplot(diamonds, aes(x=cut, fill=clarity)) + geom_bar() > ggplot(Sitka, aes(x=treat, fill=factor(Time)))+ + geom_bar()Scatter plots
# scatter of volume vs sales ggplot(txhousing, aes(x=volume, y=sales)) + geom_point()散點圖描述了成對變量(通常都是連續的)之間的協變。
geom_point()描述了映射到x和y的變量之間的協變。
散點圖是最靈活的圖之一,因為變量可以映射到許多aesthetic上,如color、shape、size和alpha。
ggplot(txhousing, aes(x=volume, y=sales, color=median, alpha=listings, size=inventory)) + geom_point()Line graphs
ggplot(txhousing, aes(x=date, y=sales, group=city)) + geom_line()線形圖用線而不是點來描述映射到x和y的變量之間的協變。
geom_line()將把所有數據視為屬于一行,除非一個變量被映射到以下aestetics之一,將數據分組為單獨的行:
- group: lines will look the same
- color: line colors will vary with mapped variable
- linetype: line patterns will vary with mapped variable
讓我們首先檢查一個沒有分組的線形圖:
ggplot(txhousing, aes(x=date, y=sales)) + geom_line()如您所見,除非數據表示單個系列,否則線形圖通常需要進行一些分組。
在geom_line()中使用color或linetype將隱式地對行進行分組。
ggplot(txhousing, aes(x=date, y=sales, color=city)) + geom_line()讓我們試著為每棵樹畫出單獨的線(生長曲線)
> ggplot(Sitka, aes(x=Time, y=size, group=tree))+ + geom_line() > ggplot(Sitka, aes(x=Time, y=size, group=tree, color=treat))+ + geom_line() > ggplot(Sitka, aes(x=Time, y=size, group=tree, linetype=treat))+ + geom_line()*Stats*
stat函數對數據進行統計轉換,通常是某種形式的匯總,如平均值、標準差或置信區間。
每個stat函數都與一個默認的geom相關聯,所以提供(render)形狀并不需要geom。
stat_summary()可能是所有stat函數中最有用的一個,它應用一個summary函數,將x變量的每個值映射到y的變量。默認的匯總函數是mean_se(),以及相關的geom geom_pointrange(),它將為x變量的每個值生成一個映射到y的變量的平均值(點)和標準誤差(線)的圖。
# summarize sales (y) for each year (x) ggplot(txhousing, aes(x=year, y=sales)) + stat_summary() > ggplot(Sitka, aes(x=Time, y=size))+ + stat_summary()stat_summary()的強大之處在于,您可以使用任何接受向量作為summary函數的函數(例如mean()、var()、max()等),并且還可以更改geom來調整繪制的形狀。
Scales
Scales定義aesthetics值映射到數據值。
自我理解:這里的Scale理解為范圍比較好。中心是aesthetics,suffix是作用的方式&功能。比如color這個aesthetic有很多類顏色,scale應該就是表示這個范圍。
這里有一個color scale的例子,它定義哪些顏色映射到treat值:
color? ? ? treat
red? ? ? ? ?ozone
blue? ? ? ?control
想象一下,我們可能想要將顏色改為“綠色”和“橙色”。
scale_函數允許用戶控制每個aesthetic的scale。這些范圍函數的名稱具有scale_aesthetic_suffix結構,其中aesthetic是一種aesthetic(如color、shpae或x)的名稱,而suffix是一些定義范圍功能的描述性詞匯。
然后,為了指定scale使用的asethetic值,向scale函數的values參數(通常)提供一個值向量。
以下是一些scale函數的例子:
- scale_color_manual(): 通過手動指定每種顏色來定義任意顏色范圍
- scale_color_hue(): 通過指定色調范圍和范圍上的顏色數量來定義均勻間隔的顏色刻度
- scale_shape_manual():通過手動指定每個形狀來定義任意形狀比例
- Function reference ? ggplot2 (tidyverse.org)https://ggplot2.tidyverse.org/reference/#section-scales這個鏈接可以查看scale函數的更多用法
?我們來看一個例子:
ggplot(diamonds, aes(x=carat, y=price, color=cut)) + geom_point()我們可以使用scale_colour_manual()?來指定我們想要使用的顏色:
ggplot(diamonds, aes(x=carat, y=price, color=cut)) + geom_point() +scale_color_manual(values=c("red", "yellow", "green", "blue", "violet"))Scale functions for the axes
記住,x和y是aesthetics,兩個軸可視化這些aesthetcis的scale。
因此,我們使用sclae函數來控制這些軸的縮放。
當y被映射到一個連續變量時,我們通常會使用scale_y_continuous()來控制它的縮放(如果y被映射到factor,則使用scale_y_discrete())。類似的函數存在于x aesthetic中。
scale_y_continuous()的一些重要參數的描述:
- breaks: 在特定數據值以及沿軸線的范圍放置標記和標簽
- labels: 標記什么
- name: 該給這個軸命名
我們當前的銷量對比圖y軸上的標簽分別為0、5000、10000和15000?
ggplot(diamonds, aes(x=carat, y=price, color=cut)) + geom_point() +scale_color_manual(values=c("red", "yellow", "green", "blue", "violet"))讓我們使用scale_y_continuous的break參數在y軸上的所有網格線上打上標簽:
ggplot(diamonds, aes(x=carat, y=price, color=cut)) + geom_point() +scale_color_manual(values=c("red", "yellow", "green", "blue", "violet")) + scale_y_continuous(breaks=c(0,2500,5000,7500,10000,12500,15000,17500))現在讓我們重新標記標記,以反映數千(美元)作為單位使用標簽:
ggplot(diamonds, aes(x=carat, y=price, color=cut)) + geom_point() +scale_color_manual(values=c("red", "yellow", "green", "blue", "violet")) + scale_y_continuous(breaks=c(0,2500,5000,7500,10000,12500,15000,17500),labels=c(0,2.5,5,7.5,10,12.5,15,17.5))最后,我們將使用name參數來重新命名y軸,以反映單位:
ggplot(diamonds, aes(x=carat, y=price, color=cut)) + geom_point() +scale_color_manual(values=c("red", "yellow", "green", "blue", "violet")) + scale_y_continuous(breaks=c(0,2500,5000,7500,10000,12500,15000,17500),labels=c(0,2.5,5,7.5,10,12.5,15,17.5),name="price(thousands of dollars)") > ggplot(diamonds, aes(x=carat, y=price,color=cut))+ + geom_point()+ + scale_color_manual(values=c('red', 'yellow', 'green', 'blue', 'violet'))+ + scale_y_continuous(breaks=c(0,2500,5000,7500,10000,12500,15000,17500),labels=c(0,2.5,5,7.5,10,12.5,15,17.5),name="price(thousands of dollars)")+ + scale_x_continuous(breaks=c(150,180,210,240),labels=c(5,6,7,8),name="time(months)")Modifying axis limits and titles
雖然我們可以使用scale_x_continuous()這樣的scale函數來控制x軸的限制和標題,但我們也可以使用以下快捷函數:
- lims(),?xlim(),?ylim(): 設置軸的限制
- xlab(),?ylab(),?ggtitle(),?labs(): 給x軸、y軸或圖形賦予標簽(標題);labs()可以為所有的aesthetic和標題設置標簽
我們可以使用labs()為整個圖形、軸和圖例(參考線)指定一個整體標題。
ggplot(diamonds, aes(x=carat, y=price, color=cut)) + geom_point() +labs(x="CARAT", y="PRICE", color="CUT", title="CARAT vs PRICE by CUT")Guides visualize scales
Guides(軸和標記)將刻scale(刻度)可視化,顯示數據值及其匹配的aesthetics。x軸是一個guide,它將數據值的映射可視化到沿著x軸的位置。一個color scale 的guide(圖例)顯示了哪些顏色映射到哪些數據值。
默認情況下顯示大多數guides。guides()函數為每個比例設置和刪除參考線。
這里我們使用guides()來移除color scale的標記(比如什么值對應什么顏色)
# notice no legend on the right anymore ggplot(txhousing, aes(x=volume, y=sales, color=median)) + geom_point() +guides(color="none")這里的作用是把顏色即其標記去掉。
Coordinate systems
坐標系定義了物體在空間上的位置。大多數圖都是用笛卡爾坐標系繪制的,這堂課上的所有圖也是如此。然而,ggplot2提供了多種坐標系統,包括極坐標系、翻轉的Carteisan(笛卡爾)坐標系和地圖投影。
Faceting (paneling)
使用faceting函數facet_wrap()和facet_grid()將圖分割成小的多個(面板)。結果圖顯示了每個圖如何沿面變量(faceting variables)變化。
facet_wrap()將多個圖形包裝到多行圖形面板中。在facet_wrap()內部,指定~,那么用+來分隔變量(比如cut變量中有5中類型,原來是放在一個圖里面,現在放在分別放在多個圖里面)。行數和列數可以用參數nrow和ncol指定。
ggplot(diamonds, aes(x=carat, y=price)) + geom_point() + facet_wrap(~cut) # create a ribbon of plots using cutfacet_grid()允許直接指定哪些變量用于沿著行和列分割數據/圖。將行分隔變量放在~之前,列分隔變量放在后面。符號?. 表示無指定。
ggplot(diamonds, aes(x=carat, y=price)) + geom_point() + facet_grid(clarity~cut) # split using clarity along rows along columns using cut > ggplot(Sitka, aes(x=Time, y=size))+ + geom_point()+ + facet_grid(.~treat)Themes
Themes控制與數據無關的圖形元素。例如:
- background color(背景色)
- size of fonts(字體大小)
- gridlines(網格線)
- color of labels(標簽顏色)
要修改這些,我們使用theme()函數,它有大量稱為theme elements的參數,這些參數控制圖的各種非數據元素。
一些theme()參數的例子,以及它們控制的圖形的哪些方面:
- axis.line?: lines forming x-axis and y-axis
- axis.line.x: just the line for x-axis
- legend.position: positioning of the legend on the graph
- panel.background: the background of the graph
- panel.border: the border around the graph
- title:?all titles on the graph
關于theme elements的全面介紹請見:
Modify components of a theme — theme ? ggplot2 (tidyverse.org)https://ggplot2.tidyverse.org/reference/theme.html
?Specifying?theme()?arguments
圖中的大多數非數據元素可以被歸類為直線(例如軸線、tick marks)、矩形(例如背景)或文本(例如軸線標題、tick labels)。每個類別都有一個相關聯的element_函數來指定控制其外觀的參數:
- element_line()?- can specify?color,?size,?linetype, etc.
- element_rect()?- can specify?fill,?color,?size, etc.
- element_text()?- can specify?family,?face,?size,?color,?angle, etc.
- element_blank()?- removes theme elements from graph
在theme()內部,我們使用適當的element_函數來控制主題元素的屬性。?
例如,x軸和y軸是線,它們都由theme()的參數axis.Line,因此它們的可視化屬性,如color和size(thickness),被指定為element_line()的參數:
ggplot(txhousing, aes(x=volume, y=sales, color=median)) + geom_point() +theme(axis.line=element_line(color="black", size=2)) # size in mm另一方面,圖形的背景,由theme()參數面板控制。Background是一個矩形,所以fill color和border color等參數可以被element_rect()指定。
ggplot(txhousing, aes(x=volume, y=sales, color=median)) + geom_point() +theme(axis.line=element_line(color="black", size=2),panel.background=element_rect(fill="white", color="gray")) # color is the border color通過element_text(),我們可以控制文本元素(比如font family或face(“bold”,“italic”,“bold.italic”))的屬性,比如title,它控制兩個軸的標題。
ggplot(txhousing, aes(x=volume, y=sales, color=median)) + geom_point() +theme(axis.line=element_line(color="black", size=2),panel.background=element_rect(fill="white", color="gray"),title=element_text(family="serif", face="bold"))注意:“sans”,“serif”和“mono”是ggplot2在不需要下載額外的R包的情況下唯一可用的字體系列。有關更多信息,請見:
RPubs - tidbitR - Changing Font family in ggplothttps://rpubs.com/vprabhuram/222833
?最后,一些theme()參數不使用element_函數來控制它們的屬性,比如legend.position,它只接受值“none”、“left”、“right”、“bottom”和“top”。
ggplot(txhousing, aes(x=volume, y=sales, color=median)) + geom_point() +theme(axis.line=element_line(color="black", size=2),panel.background=element_rect(fill="white", color="gray"),title=element_text(family="serif", face="bold"),legend.position="bottom")然后,我們可以在theme()中使用legend.text=element.text()來旋轉圖例標簽(此處不展示)。
?Modify components of a theme — theme ? ggplot2 (tidyverse.org)https://ggplot2.tidyverse.org/reference/theme.html
當使用theme()時記得使用這個網址。
> ggplot(Sitka, aes(x=Time, y=size))+ + geom_point()+ + theme(axis.ticks=element_line(color="white"))?Changing the overall look with complete themes
ggplot2包提供了幾個完整的主題,這些主題對圖形的整體背景外觀進行了一些更改(參見此處獲取完整的描述)。
一些例子:
- theme_bw()
- theme_light()
- theme_dark()
- theme_classic()
主題通常會調整背景的顏色和組成圖形非數據部分的大多數線條的顏色。
theme_classic()模仿了基R圖形的外觀(應該就是保持原樣吧):
ggplot(txhousing, aes(x=volume, y=sales, color=median)) + geom_point() +theme_classic()Theme_dark()在外觀上做了一個巨大的改變:
ggplot(txhousing, aes(x=volume, y=sales, color=median)) + geom_point() +theme_dark()Saving plots to files
ggsave()使保存圖變得容易。默認情況下,最后顯示的圖形會被保存,但是我們也可以將圖形保存到R對象中。
ggsave嘗試從文件擴展名中猜測用來保存圖像的設備,因此使用有意義的擴展名。可用的設備包括eps/ps, tex (pictex),pdf, jpeg, tiff, png, bmp, svg和wmf。
ggsave()其他的重要參數:
?
- width
- height
- units:?units?of?width?and?height?of plot file ("in",?"cm"?or?"mm")
- dpi: plot resolution in dots per inch以每英寸點為單位的繪圖分辨率
- plot: name of object with stored plot
From idea to final graphic: graphing the?Rabbit?data set {MASS}
為了練習使用圖形語法的元素,我們將從我們想要顯示的內容的想法開始,一步一步地,我們將添加和調整圖形,直到我們覺得它可以與觀眾分享。
在下一個圖中,我們將可視化Rabbit數據集中的數據,它也是由MASS包加載的。
> library(ggplot2) > library(MASS) > data(Rabbit) > str(Rabbit)Rabbit數據集描述了一個實驗,其中:
5只兔分別用生理鹽水(對照組)和血清素受體拮抗劑(阻斷劑)“MDL 72222”治療。
在注射治療藥物或對照藥物后,每只家兔注射6次遞增劑量的苯雙胍,使血壓隨劑量升高。
測量血壓的變化作為結果。
每只家兔測血壓12次,治療組和對照組各測6次
目的是測試血壓的變化是否依賴于血清素受體的激活。
數據集包含以下5個變量的60行(5只兔子測量12次):
BPchange:相對于實驗開始時的血壓變化
dose:苯基雙胍的劑量(單位:微克)
Run: trial的標簽
Treatment:對照組或MDL
Animal:動物ID(“R1”至“R5”)
The idea of the graph
在藥物研究中,我們想要創建一個劑量-反應曲線。在這項研究中,我們想了解在生理鹽水(對照)和血清素拮抗劑MDL 7222(治療)存在的情況下,血壓變化與苯雙胍(一種血壓升高藥物)的劑量是如何相關的。
需要考慮的問題:
在對照組和治療藥物下,每只兔子都被測量了6次(不同劑量的血壓興奮劑)。我們如何區分這兩種情況下的劑量反應曲線?
我們只研究了5只動物(在給予對照和治療藥物后,每只注射6劑量的苯基雙胍),所以我們可以將所有單個兔子的曲線擬合在一張圖上
所以,我們想要一個代表每只兔子的劑量-反應曲線的圖表,最好是每只兔子的治療和控制條件的單獨曲線。
讓我們一步一步地構建這個圖。
Rabbit graph 1
什么geom會需要到畫出計量—反應曲線?
geom_line()
需要的aesthetic是什么?
x與y
Rabbit graph 2
ggplot(Rabbit, aes(x=Dose, y=BPchange)) +geom_line()這顯然不是我們想要的——這個圖將數據視為所有數據都屬于一條線上。我們想要通過兔子(可變動物)分開的線。我們如何指定它呢?
將Animal映射到一個組aesthetics,如group,color,linetype.
讓我們想象一下,我們被限制在生成一個無色的圖形,因此我們不能使用color。我們將代替使用linetype來分隔Animal。
Rabbit graph 3
ggplot(Rabbit, aes(x=Dose, y=BPchange, linetype=Animal)) +geom_line()這看起來還是不對嗎?為什么?
記住,每只兔子在每個劑量下都進行了兩次測試,一次是在MDL 7222治療藥物的存在下,一次是在對照組藥物的存在下。每個動物的兩條分開的曲線仍然被連接成一條。
因此,我們需要將每個動物的治療曲線與對照曲線分開。我們怎樣才能做到呢?
一種方法是將Treatment分配給像color一樣的分組aesthetics。
ggplot(Rabbit, aes(x=Dose, y=BPchange, color=Treatment, linetype=Animal)) +geom_line()然而,我們把自己限制在無色的圖形上。你能想到其他方法來分離曲線嗎?
用Faceting
Rabbit graph 4
ggplot(Rabbit, aes(x=Dose, y=BPchange, linetype=Animal)) +geom_line() +facet_wrap(~Treatment)現在我們終于開始看到我們想要的圖形了!
僅僅根據linetype來區分線條可能有點困難。讓我們向圖形中添加一些點,但通過Treatment改變點的形狀。
如何向隨形狀變化的圖形添加點?
geom_point()將shape映射到Animal
Rabbit graph 5
ggplot(Rabbit, aes(x=Dose, y=BPchange, linetype=Animal, shape=Animal)) +geom_line() +facet_wrap(~Treatment) +geom_point()取得良好進展!
現在,假設我們想要選擇繪制的形狀,而不是使用默認值。我們需要什么函數(或什么類型的函數)來改變形狀?
一個scale函數!具體來說,scale_shape_manual()。這些形狀是用0到25之間的整數代碼指定的。查看幫助頁面的Points(?dot或?pch)來查看代碼和形狀的表格。
Rabbit graph 6
ggplot(Rabbit, aes(x=Dose, y=BPchange, shape=Animal, linetype=Animal)) +geom_line() +facet_wrap(~Treatment) + geom_point() + scale_shape_manual(values=c(0, 3, 8, 16, 17))好的!現在我們已經完成了向圖中添加數據的工作。現在我們繼續進行一些微調。
首先,讓我們改變x軸和y軸的標題。什么函數可以改變這兩個?
lab()
Rabbit graph 7
ggplot(Rabbit, aes(x=Dose, y=BPchange, shape=Animal, linetype=Animal)) +geom_point() + geom_line() +facet_wrap(~Treatment) + scale_shape_manual(values=c(0, 3, 8, 16, 17)) +labs(x="Dose(mcg)", y="Change in blood pressure")差不多了!
假設我們不喜歡灰色背景和白色網格線,而是想使用白色背景和灰色網格線。
我們將使用什么功能來調整這些元素?
- theme()
控制圖形背景的theme()參數是panel.background。我們應該使用哪個element_函數來指定panel.background的參數?
- element_rect()
?theme()參數panel.grid控制網格線。我們應該使用哪個element_函數來指定網格線的參數?
?element_line()
Rabbit graph 8
ggplot(Rabbit, aes(x=Dose, y=BPchange, shape=Animal, linetype=Animal)) +geom_point() +geom_line() +facet_wrap(~Treatment) +scale_shape_manual(values=c(0, 3, 8, 16, 17)) +labs(x="Dose(mcg)", y="Change in blood pressure") +theme(panel.background = element_rect(fill="white"),panel.grid=element_line(color="gray90"))最后一個步驟!
現在我們想要使用theme()來調整軸、legend和面板標題(“Control”和“MDL”)以使用粗體。
我們將使用的theme參數是title和strip.text。我們應該使用哪個element_函數來指定這些參數?
- element_text()
我們將在element_text中使用face參數將標題設置為“粗體”。
Rabbit graph finished
ggplot(Rabbit, aes(x=Dose, y=BPchange, shape=Animal, linetype=Animal)) +geom_point() +geom_line() +facet_wrap(~Treatment) +scale_shape_manual(values=c(0, 3, 8, 16, 17)) +labs(x="Dose(mcg)", y="Change in blood pressure") +theme(panel.background = element_rect(fill="white"),panel.grid=element_line(color="gray90"),title=element_text(face="bold"),strip.text=element_text(face="bold"))Advice for working with?ggplot2
New dataset?birthwt?{MASS}
birthwt數據集包含與低出生體重相關的危險因素的數據。
數據由10個變量的189個觀測值組成,均為數值:
- low: 0/1 indicator of birth weight < 2.5 kg
- age: mother’s age
- lwt: mother’s weight in pounds
- race: mother’s race, (1=white, 2=black, 3=other)
- smoke: 0/1 indicator of smoking during pregnancy
- ptl: number of previous premature labors(早產次數)
- ht: 0/1 indicator of history of hypertension(高血壓)
- ui: 0/1 indicator of uterine irritability(子宮刺激性)
- ftv: number of physician visits during first trimester(前三個月)
- bwt: birth weight
讓我們先看看birthwt數據集的結構,以了解如何測量變量。
> data(birthwt) > str(birthwt)Aesthetics, numeric and factor (categorical) variables
數據集中的變量通??梢苑譃?strong>數值變量(numeric variables)(數值是表示數量的有意義的表示)和因子(分類)變量(factor (categorical) variables)(數值通常是表示類別而不是數量的成員關系的代碼)。
In?R, we can encode variables as “factors” with the?factor()?function.
一些aesthetics可以映射到數值或分類變量,并且將以不同的方式scaled。
包括:
- x?and?y: continuous or discrete axes
- color?and?fill: 顏色梯度scales或均勻間隔的色調scales
Other aesthetics can only be mapped to categorical variables:
- shape
- linetype
And finally some aethetics?should?only be mapped to numeric variables (a warning is issued if mapped to a categorical variable):
- size
- alpha
Aesthetic scales are formed differently for numeric and factor variables
讓我們看看當使用birthwt數據集(其中所有的變量最初都是數值型的)映射到不同類型的變量時,aesthetic是如何表現的。
當color被映射到一個數值變量時,將使用一個顏色梯度scale:
注意:盡管我們只是使用race作為數值變量來演示ggplot如何處理它,但我們不建議將分類變量作為數值變量對待。
當將顏色映射到一個因子變量時,將使用均勻間隔的色調的顏色刻度。我們可以使用factor()將數字變量轉換為aes()中的因子:
ggplot(birthwt, aes(x=age, y=bwt, color=factor(race))) +geom_point()如果我們試圖將shape映射到race的數值版本,就會出現錯誤,因為shape只接受因子變量。
Shape接受race的因子表示:?
ggplot(birthwt, aes(x=age, y=bwt, shape=factor(race))) +geom_point()最后,像alpha和size這樣的aesthetic應該只用于真正的數值變量,如果變量是一個因子,則會發出警告:
ggplot(birthwt, aes(x=age, y=bwt, size=factor(race))) +geom_point() ## Warning: Using size for a discrete variable is not advised.Convert categorical variables to factors before graphing
我們建議在繪圖之前將所有分類變量轉換為因子,原因如下:
- 我們不需要在每次創建圖形時都將變量包含在factor()中
- We can label the levels to use in all graphs
- ggplot2?will discourage mapping a factor variable to an inappropriate aesthetic like?size
?Overlapping data points in scatter plots
?當兩個數據點在圖上有相同的值時,它們通常會占據相同的位置,導致其中一個遮蓋了另一個。
?在這個例子中,我們將race(一個factor變量)映射到x,將年齡(以年為單位)映射到y:
ggplot(birthwt, aes(x=race, y=age)) +geom_point()數據集中有189個數據點,但遠遠少于圖中可見的189個點,因為很多點是完全重疊的。
為了解決這個問題,我們有一個“位置調整”的選擇,它可以在geom函數的position參數中指定。?
對于geom_point(),我們嘗試用兩個中的一個:
- position="jitter": add a little random noise to position
- position="identity": overlay points (覆蓋點)(the default for?geom_point())
通過在之前的散點圖中添加position="jitter",我們可以更好地看到在每個年齡階段有多少個點:
ggplot(birthwt, aes(x=race, y=age)) +geom_point(position="jitter")總結
以上是生活随笔為你收集整理的UCLA-(R Graphics: Intro to ggplot2)笔记的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 百度网盘分享文件已经被取消的解决办法
- 下一篇: IOS9 xcode7 You must