文章目錄
- 通用教程簡介(Introduction To ggplot2)
- 2 ggplot2入門筆記2—通用教程ggplot2簡介
- 1. 瞭解ggplot語法(Understanding the ggplot Syntax)
- 2. 如何製作一個簡單的散點圖(How to Make a Simple Scatterplot)
- 3. 如何調整XY軸範圍(How to Adjust the X and Y Axis Limits)
- 4. 如何更改標題和軸標籤(How to Change the Title and Axis Labels)
- 5. 如何更改點的顏色和大小(How to Change the Color and Size of Points)
- 5.1 如何將顏色和尺寸更改爲靜態?(How to Change the Color and Size To Static?)
- 5.2 如何更改顏色以在另一列中反映類別?(How to Change the Color To Reflect Categories in Another Column?)
- 6. 如何更改X軸文本和刻度的位置(How to Change the X Axis Texts and Ticks Location)
通用教程簡介(Introduction To ggplot2)
代碼下載地址
以前,我們看到了使用ggplot2軟件包製作圖表的簡短教程。它很快涉及製作ggplot的各個方面。現在,這是一個完整而完整的教程。現在討論如何構造和自定義幾乎所有ggplot。它涉及的原則,步驟和微妙之處,使圖像的情節有效和更具視覺吸引力。因此,出於實用目的,我希望本教程可以作爲書籤參考,對您日常的繪圖工作很有用。
這是ggplot2的三部分通用教程的第1部分,ggplot2是R中的美觀(非常流行)的圖形框架。該教程主要針對具有R編程語言的一些基本知識並希望製作複雜且美觀的圖表的用戶與R ggplot2。
- ggplot2簡介(Introduction to ggplot2)
- 自定義外觀(Customizing the Look and Feel)
- 前50個ggplot2可視化效果(top 50 ggplot2 Visualizations)
ggplot2簡介涵蓋了有關構建簡單ggplot以及修改組件和外觀的基本知識;自定義外觀是關於圖像的自定義,如使用多圖,自定義佈局操作圖例、註釋;前50個ggplot2可視化效果應用在第1部分和第2部分中學到的知識來構造其他類型的ggplot,例如條形圖,箱形圖等。
2 ggplot2入門筆記2—通用教程ggplot2簡介
本章節簡介涵蓋了有關構建簡單ggplot以及修改組件和外觀的基本知識,該章節主要內容有:
- 瞭解ggplot語法(Understanding the ggplot Syntax)
- 如何製作一個簡單的散點圖(How to Make a Simple Scatterplot)
- 如何調整XY軸範圍(How to Adjust the X and Y Axis Limits)
- 如何更改標題和軸標籤(How to Change the Title and Axis Labels)
- 如何更改點的顏色和大小(How to Change the Color and Size of Points)
- 如何更改X軸文本和刻度的位置(How to Change the X Axis Texts and Ticks Location)
參考文檔
http://r-statistics.co/Complete-Ggplot2-Tutorial-Part1-With-R-Code.html
1. 瞭解ggplot語法(Understanding the ggplot Syntax)
如果您是初學者或主要使用基本圖形,則構造ggplots的語法可能會令人困惑。主要區別在於,與基本圖形不同,ggplot適用於數據表而不是單個矢量。繪圖所需的所有數據通常都包含在提供給ggplot()本身的數據框中,或者可以提供給各個geom。第二個值得注意的功能是,您可以通過向使用該ggplot()功能創建的現有圖上添加更多層(和主題)來繼續增強圖。
讓我們根據midwest數據集初始化一個基本的ggplot
# Setup
# #關閉科學記數法,如1e+06
# turn off scientific notation like 1e+06
options(scipen=999)
library(ggplot2)
# load the data 載入數據
data("midwest", package = "ggplot2")
# 顯示數據
head(midwest)
# Init Ggplot 初始化圖像
# area and poptotal are columns in 'midwest'
ggplot(midwest, aes(x=area, y=poptotal))
Warning message:
"package 'ggplot2' was built under R version 3.6.1"
PID | county | state | area | poptotal | popdensity | popwhite | popblack | popamerindian | popasian | ... | percollege | percprof | poppovertyknown | percpovertyknown | percbelowpoverty | percchildbelowpovert | percadultpoverty | percelderlypoverty | inmetro | category |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
<int> | <chr> | <chr> | <dbl> | <int> | <dbl> | <int> | <int> | <int> | <int> | ... | <dbl> | <dbl> | <int> | <dbl> | <dbl> | <dbl> | <dbl> | <dbl> | <int> | <chr> |
561 | ADAMS | IL | 0.052 | 66090 | 1270.9615 | 63917 | 1702 | 98 | 249 | ... | 19.63139 | 4.355859 | 63628 | 96.27478 | 13.151443 | 18.01172 | 11.009776 | 12.443812 | 0 | AAR |
562 | ALEXANDER | IL | 0.014 | 10626 | 759.0000 | 7054 | 3496 | 19 | 48 | ... | 11.24331 | 2.870315 | 10529 | 99.08714 | 32.244278 | 45.82651 | 27.385647 | 25.228976 | 0 | LHR |
563 | BOND | IL | 0.022 | 14991 | 681.4091 | 14477 | 429 | 35 | 16 | ... | 17.03382 | 4.488572 | 14235 | 94.95697 | 12.068844 | 14.03606 | 10.852090 | 12.697410 | 0 | AAR |
564 | BOONE | IL | 0.017 | 30806 | 1812.1176 | 29344 | 127 | 46 | 150 | ... | 17.27895 | 4.197800 | 30337 | 98.47757 | 7.209019 | 11.17954 | 5.536013 | 6.217047 | 1 | ALU |
565 | BROWN | IL | 0.018 | 5836 | 324.2222 | 5264 | 547 | 14 | 5 | ... | 14.47600 | 3.367680 | 4815 | 82.50514 | 13.520249 | 13.02289 | 11.143211 | 19.200000 | 0 | AAR |
566 | BUREAU | IL | 0.050 | 35688 | 713.7600 | 35157 | 50 | 65 | 195 | ... | 18.90462 | 3.275891 | 35107 | 98.37200 | 10.399635 | 14.15882 | 8.179287 | 11.008586 | 0 | AAR |
上面繪製了一個空白ggplot。即使指定了x和y,也沒有點或線。這是因爲ggplot並不假定您要繪製散點圖或折線圖。我只告訴ggplotT使用什麼數據集,哪些列應該用於X和Y軸。我沒有明確要求它畫出任何點。還要注意,該aes()功能用於指定X和Y軸。這是因爲,必須在aes()函數中指定屬於源數據幀的任何信息。
2. 如何製作一個簡單的散點圖(How to Make a Simple Scatterplot)
讓我們通過使用稱爲的geom層添加散點圖,在空白ggplot基礎製作一個散點圖geom_point。
library(ggplot2)
ggplot(midwest, aes(x=area, y=poptotal)) +
geom_point()
我們得到了一個基本的散點圖,其中每個點代表一個縣。但是,它缺少一些基本組成部分,例如繪圖標題,有意義的軸標籤等。此外,大多數點都集中在繪圖的底部,這不太好。您將在接下來的步驟中看到如何糾正這些問題。
像geom_point()一樣,有許多這樣的geom層,我們將在本教程系列的後續部分中看到。現在,讓我們使用geom_smooth(method=‘lm’)添加一個平滑層。由於該方法被設置爲lm(線性模型的簡稱),所以它會畫出最適合的擬合直線。
g <- ggplot(midwest, aes(x=area, y=poptotal)) +
geom_point() +
# set se=FALSE to turnoff confidence bands
# 設置se=FALSE來關閉置信區間
geom_smooth(method="lm", se=TRUE)
plot(g)
最合適的線是藍色。您能找到其他method可用的選項geom_smooth嗎?(注意:請參閱geom_smooth)。您可能已經注意到,大多數點都位於圖表的底部,看起來並不好看。因此,讓我們更改Y軸限制以關注下半部分。
3. 如何調整XY軸範圍(How to Adjust the X and Y Axis Limits)
X軸和Y軸範圍可以通過兩種方式控制。
3.1 方法1:通過刪除範圍之外的點
與原始數據相比,這將更改最佳擬合線或平滑線。這可以通過xlim()和ylim()完成。可以傳遞長度爲2的數值向量(具有最大值和最小值)或僅傳遞最大值和最小值本身。
library(ggplot2)
# set se=FALSE to turnoff confidence bands
# 設置se=FALSE來關閉置信區間
g <- ggplot(midwest, aes(x=area, y=poptotal)) +
geom_point() +
geom_smooth(method="lm")
# Delete the points outside the limits
# deletes points 刪除點
g + xlim(c(0, 0.1)) + ylim(c(0, 1000000))
# g + xlim(0, 0.1) + ylim(0, 1000000)
Warning message:
"Removed 5 rows containing non-finite values (stat_smooth)."
Warning message:
"Removed 5 rows containing missing values (geom_point)."
在這種情況下,圖表不是從頭開始構建的,而是建立在g之上的。這是因爲先前的圖g以ggplot對象存儲爲,該對象在被調用時將重現原始圖。使用ggplot,您可以在該圖的頂部添加更多的圖層,主題和其他設置。
您是否注意到最佳擬合線與原始圖相比變得更加水平?這是因爲,當使用xlim()和時ylim(),指定範圍之外的點將被刪除,並且在繪製最佳擬合線(使用geom_smooth(method=‘lm’))時將不考慮這些點。當您希望知道移除某些極值(或離羣值)時最佳擬合線將如何變化時,此功能可能會派上用場。
3.2 方法2:放大
另一種方法是通過放大感興趣的區域而不刪除點來更改X和Y軸限制。這是使用coord_cartesian()完成的。讓我們將該圖存儲爲g1,由於考慮了所有要點,因此最佳擬合線沒有改變。
library(ggplot2)
g <- ggplot(midwest, aes(x=area, y=poptotal)) +
geom_point() +
# set se=FALSE to turnoff confidence bands
geom_smooth(method="lm")
# Zoom in without deleting the points outside the limits.
# As a result, the line of best fit is the same as the original plot.
# 放大而不刪除超出限制的點。因此,最佳擬合線與原始圖相同。
g1 <- g + coord_cartesian(xlim=c(0,0.1), ylim=c(0, 1000000))
plot(g1)
4. 如何更改標題和軸標籤(How to Change the Title and Axis Labels)
我將其存儲爲g1。讓我們爲X和Y軸添加繪圖標題和標籤。這可以一次性使用來完成labs()與功能title,x和y參數。另一種選擇是使用ggtitle(),xlab()和ylab()
library(ggplot2)
# 畫圖
# set se=FALSE to turnoff confidence bands
g <- ggplot(midwest, aes(x=area, y=poptotal)) + geom_point() + geom_smooth(method="lm")
# 限制範圍
g1 <- g + coord_cartesian(xlim=c(0,0.1), ylim=c(0, 1000000)) # zooms in
# Add Title and Labels
# 添加標籤,標題名,小標題名,說明文字
g1 + labs(title="Area Vs Population", subtitle="From midwest dataset", y="Population", x="Area", caption="Midwest Demographics")
# 另外一種方法
g1 + ggtitle("Area Vs Population", subtitle="From midwest dataset") + xlab("Area") + ylab("Population")
優秀!因此,這是完整功能調用。
# Full Plot call
library(ggplot2)
ggplot(midwest, aes(x=area, y=poptotal)) +
geom_point() +
geom_smooth(method="lm") +
coord_cartesian(xlim=c(0,0.1), ylim=c(0, 1000000)) +
labs(title="Area Vs Population", subtitle="From midwest dataset", y="Population", x="Area", caption="Midwest Demographics")
5. 如何更改點的顏色和大小(How to Change the Color and Size of Points)
本節主要內容有:
- 如何將顏色和尺寸更改爲靜態?(How to Change the Color and Size To Static?)
- 如何更改顏色以在另一列中反映類別?(How to Change the Color To Reflect Categories in Another Column?)
5.1 如何將顏色和尺寸更改爲靜態?(How to Change the Color and Size To Static?)
我們可以通過修改相應的幾何圖形來改變幾何圖形圖層的美感。讓我們將點和線的顏色更改爲靜態值。
library(ggplot2)
# 畫圖
ggplot(midwest, aes(x=area, y=poptotal)) +
# Set static color and size for points
# 設置固定顏色和尺寸
geom_point(col="steelblue", size=3) +
# change the color of line
# 更改擬合直線顏色
geom_smooth(method="lm", col="firebrick") +
coord_cartesian(xlim=c(0, 0.1), ylim=c(0, 1000000)) +
labs(title="Area Vs Population", subtitle="From midwest dataset", y="Population", x="Area", caption="Midwest Demographics")
5.2 如何更改顏色以在另一列中反映類別?(How to Change the Color To Reflect Categories in Another Column?)
假設我們要根據源數據集中的另一列更改顏色midwest,則必須在aes()函數內指定顏色。
library(ggplot2)
gg <- ggplot(midwest, aes(x=area, y=poptotal)) +
# Set color to vary based on state categories.
# 根據狀態類別將顏色設置爲不同。
geom_point(aes(col=state), size=3) +
geom_smooth(method="lm", col="firebrick", size=2) +
coord_cartesian(xlim=c(0, 0.1), ylim=c(0, 1000000)) +
labs(title="Area Vs Population", subtitle="From midwest dataset", y="Population", x="Area", caption="Midwest Demographics")
plot(gg)
現在,每個點都基於aes所屬的狀態(col=state)上色。不只是顏色,大小、形狀、筆劃(邊界的厚度)和填充(填充顏色)都可以用來區分分組。作爲附加的優點,圖例將自動添加。如果需要,可以通過在theme()函數中將legend.position設置爲None來刪除它。
# remove legend 移除圖例
gg + theme(legend.position="None")
另外,您可以用調色板完全更改顏色。
# change color palette 更改調色板
gg + scale_colour_brewer(palette = "Set1")
在RColorBrewer軟件包中可以找到更多這樣的調色板,具體顏色顯示見網頁
library(RColorBrewer)
head(brewer.pal.info, 10)
maxcolors | category | colorblind | |
---|---|---|---|
<dbl> | <fct> | <lgl> | |
BrBG | 11 | div | TRUE |
PiYG | 11 | div | TRUE |
PRGn | 11 | div | TRUE |
PuOr | 11 | div | TRUE |
RdBu | 11 | div | TRUE |
RdGy | 11 | div | FALSE |
RdYlBu | 11 | div | TRUE |
RdYlGn | 11 | div | FALSE |
Spectral | 11 | div | FALSE |
Accent | 8 | qual | FALSE |
6. 如何更改X軸文本和刻度的位置(How to Change the X Axis Texts and Ticks Location)
本節主要內容有:
- 如何更改X和Y軸文本及其位置?(How to Change the X and Y Axis Text and its Location?)
- 如何通過設置原始值的格式爲軸標籤編寫自定義文本?(How to Write Customized Texts for Axis Labels, by Formatting the Original Values?)
- 如何使用預置主題一次性定製整個主題?(How to Customize the Entire Theme in One Shot using Pre-Built Themes?)
6.1 如何更改X和Y軸文本及其位置?(How to Change the X and Y Axis Text and its Location?)
好了,現在讓我們看看如何更改X和Y軸文本及其位置。這涉及兩個方面:breaks和labels。
第1步:設置breaks
座標軸間隔breaks的範圍應該與X軸變量相同。注意,我使用的是scale_x_continuous,因爲X軸變量是連續變量。如果它是一個日期變量,那麼可以使用scale_x_date。與scale_x_continuous()類似,scale_y_continuous()也可用於Y軸。
library(ggplot2)
# Base plot
gg <- ggplot(midwest, aes(x=area, y=poptotal)) +
# Set color to vary based on state categories
# 設置顏色
geom_point(aes(col=state), size=3) +
geom_smooth(method="lm", col="firebrick", size=2) +
coord_cartesian(xlim=c(0, 0.1), ylim=c(0, 1000000)) +
labs(title="Area Vs Population", subtitle="From midwest dataset", y="Population", x="Area", caption="Midwest Demographics")
# Change breaks
# 改變間距
gg + scale_x_continuous(breaks=seq(0, 0.1, 0.01))
第2步:更改labels
可以選擇更改labels軸刻度。labels取與長度相同的向量breaks。通過設置labels從a到k的字母進行演示(儘管在這種情況下它沒有任何意義)。
library(ggplot2)
# Base plot
gg <- ggplot(midwest, aes(x=area, y=poptotal)) +
# Set color to vary based on state categories
# 設置顏色
geom_point(aes(col=state), size=3) +
geom_smooth(method="lm", col="firebrick", size=2) +
coord_cartesian(xlim=c(0, 0.1), ylim=c(0, 1000000)) +
labs(title="Area Vs Population", subtitle="From midwest dataset", y="Population", x="Area", caption="Midwest Demographics")
# Change breaks + label
# letters字母表
gg + scale_x_continuous(breaks=seq(0, 0.1, 0.01), labels = letters[1:11])
如果需要反轉刻度,請使用scale_x_reverse()/scale_y_reverse()
library(ggplot2)
# Base plot
gg <- ggplot(midwest, aes(x=area, y=poptotal)) +
# Set color to vary based on state categories
# 設置顏色
geom_point(aes(col=state), size=3) +
geom_smooth(method="lm", col="firebrick", size=2) +
coord_cartesian(xlim=c(0, 0.1), ylim=c(0, 1000000)) +
labs(title="Area Vs Population", subtitle="From midwest dataset", y="Population", x="Area", caption="Midwest Demographics")
# Reverse X Axis Scale
# 反轉x軸
gg + scale_x_reverse()
6.2 如何通過設置原始值的格式爲軸標籤編寫自定義文本?(How to Write Customized Texts for Axis Labels, by Formatting the Original Values?)
讓我們設置Y軸文本的breaks,並設置X軸和Y軸標籤。我用了兩種方法格式化標籤。方法1:使用sprintf()。(在下面的示例中,將其格式化爲%)* 方法2:使用自定義的用戶定義函數。(按1000到1K的比例格式化)
library(ggplot2)
# Base plot
gg <- ggplot(midwest, aes(x=area, y=poptotal)) +
# Set color to vary based on state categories
# 設置顏色
geom_point(aes(col=state), size=3) +
geom_smooth(method="lm", col="firebrick", size=2) +
coord_cartesian(xlim=c(0, 0.1), ylim=c(0, 1000000)) +
labs(title="Area Vs Population", subtitle="From midwest dataset", y="Population", x="Area", caption="Midwest Demographics")
# Change Axis Texts
gg +
# 更改x軸
scale_x_continuous(breaks=seq(0, 0.1, 0.01), labels = sprintf("%1.2f%%", seq(0, 0.1, 0.01))) +
# 更改y軸
scale_y_continuous(breaks=seq(0, 1000000, 200000), labels = function(x){paste0(x/1000, 'K')})
6.3 如何使用預置主題一次性定製整個主題?(How to Customize the Entire Theme in One Shot using Pre-Built Themes?)
最後,我們可以使用預先構建的主題來更改整個主題本身,而不是單獨更改主題組件。幫助頁面?theme_bw顯示了所有可用的內置主題。這通常是通過兩種方式來實現的。在繪製ggplot之前,使用theme_set()設置主題。請注意,此設置將影響將來的所有繪圖。或者繪製ggplot,然後添加整個主題設置(例如theme_bw())
library(ggplot2)
# Base plot
gg <- ggplot(midwest, aes(x=area, y=poptotal)) +
# Set color to vary based on state categories.
geom_point(aes(col=state), size=3) +
geom_smooth(method="lm", col="firebrick", size=2) +
coord_cartesian(xlim=c(0, 0.1), ylim=c(0, 1000000)) +
labs(title="Area Vs Population", subtitle="From midwest dataset", y="Population", x="Area", caption="Midwest Demographics")
gg <- gg + scale_x_continuous(breaks=seq(0, 0.1, 0.01))
# method 1: Using theme_set()
theme_set(theme_classic())
gg
# method 2: Adding theme Layer itself.
# 添加主題層
gg + theme_bw() + labs(subtitle="BW Theme")
gg + theme_classic() + labs(subtitle="Classic Theme")