[R语言] ggplot2入门笔记2—通用教程ggplot2简介

通用教程简介(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以及修改组件和外观的基本知识,该章节主要内容有:

  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)
  6. 如何更改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"
A tibble: 6 × 28
PIDcountystateareapoptotalpopdensitypopwhitepopblackpopamerindianpopasian...percollegepercprofpoppovertyknownpercpovertyknownpercbelowpovertypercchildbelowpovertpercadultpovertypercelderlypovertyinmetrocategory
<int><chr><chr><dbl><int><dbl><int><int><int><int>...<dbl><dbl><int><dbl><dbl><dbl><dbl><dbl><int><chr>
561ADAMS IL0.052660901270.961563917170298249...19.631394.3558596362896.2747813.15144318.0117211.00977612.4438120AAR
562ALEXANDERIL0.01410626 759.0000 7054349619 48...11.243312.8703151052999.0871432.24427845.8265127.38564725.2289760LHR
563BOND IL0.02214991 681.409114477 42935 16...17.033824.4885721423594.9569712.06884414.0360610.85209012.6974100AAR
564BOONE IL0.017308061812.117629344 12746150...17.278954.1978003033798.47757 7.20901911.17954 5.536013 6.2170471ALU
565BROWN IL0.018 5836 324.2222 5264 54714 5...14.476003.367680 481582.5051413.52024913.0228911.14321119.2000000AAR
566BUREAU IL0.05035688 713.760035157 5065195...18.904623.2758913510798.3720010.39963514.15882 8.17928711.0085860AAR

png

上面绘制了一个空白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()

png

我们得到了一个基本的散点图,其中每个点代表一个县。但是,它缺少一些基本组成部分,例如绘图标题,有意义的轴标签等。此外,大多数点都集中在绘图的底部,这不太好。您将在接下来的步骤中看到如何纠正这些问题。
像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)

png

最合适的线是蓝色。您能找到其他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)."

png

在这种情况下,图表不是从头开始构建的,而是建立在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)

png

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

png

# 另外一种方法
g1 + ggtitle("Area Vs Population", subtitle="From midwest dataset") + xlab("Area") + ylab("Population")

png

优秀!因此,这是完整功能调用。

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

png

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

png

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)

png

现在,每个点都基于aes所属的状态(col=state)上色。不只是颜色,大小、形状、笔划(边界的厚度)和填充(填充颜色)都可以用来区分分组。作为附加的优点,图例将自动添加。如果需要,可以通过在theme()函数中将legend.position设置为None来删除它。

# remove legend 移除图例
gg + theme(legend.position="None")  

png

另外,您可以用调色板完全更改颜色。

# change color palette 更改调色板
gg + scale_colour_brewer(palette = "Set1")  

png

在RColorBrewer软件包中可以找到更多这样的调色板,具体颜色显示见网页

library(RColorBrewer)
head(brewer.pal.info, 10)
A data.frame: 10 × 3
maxcolorscategorycolorblind
<dbl><fct><lgl>
BrBG11div TRUE
PiYG11div TRUE
PRGn11div TRUE
PuOr11div TRUE
RdBu11div TRUE
RdGy11div FALSE
RdYlBu11div TRUE
RdYlGn11div FALSE
Spectral11div FALSE
Accent 8qualFALSE

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

png

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

png

如果需要反转刻度,请使用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()

png

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

png

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

png

# method 2: Adding theme Layer itself.
# 添加主题层
gg + theme_bw() + labs(subtitle="BW Theme")

png

gg + theme_classic() + labs(subtitle="Classic Theme")

png

posted @ 2020-03-21 11:04  落痕的寒假  阅读(90)  评论(0编辑  收藏  举报