[R语言] ggplot2入门笔记1—ggplot2简要教程

1 ggplot2入门笔记1—ggplot2简要教程

代码下载地址
ggplot2是R中最优雅,美观的图形框架。它具有精心设计的结构。本教程重点介绍可用于制作任何ggplot的基础结构。但是,在ggplot2中绘制图的方式与使学习曲线陡峭的基本图形截然不同。因此,将您对基本图形的了解留在后面并继续。您距离破解ggplot拼图只有5个步骤。该章节主要内容有:

  1. 设置 The Setup
  2. 图层 The Layers
  3. 标签 The Labels
  4. 主题 The Theme
  5. 分面 The Facets
  6. 常用函数 Commonly Used Features

参考文档

http://r-statistics.co/ggplot2-Tutorial-With-R.html

1. 设置 The Setup

首先,您需要告诉ggplot使用什么数据集。这是使用ggplot(df)函数完成的,其中df是一个数据框,其中包含制作绘图所需的所有功能。这是最基本的步骤。与基础图形不同,ggplot不会将矢量作为参数。
您可以aes()通过指定数据集中的各个变量,将想要应用到ggplot(内部参数)的任何美学效果添加到其中-例如X和Y轴。颜色,大小,形状基于其更改的变量也可以在此处自行指定。此处指定的美学将被您随后添加的所有geom层继承。如果以后打算添加更多的图层(可能是折线图顶部的条形图),则可以在添加这些图层时指定各自的外观。

下面,我展示了一些如何在自身diamonds随附的数据集中使用ggplot的示例ggplot2。但是,在添加几何图层之前,不会展示任何图像。

# 调用ggplot2库
library(ggplot2)
# 展示金刚石数据集
head(diamonds)
Warning message:
"package 'ggplot2' was built under R version 3.6.1"
A tibble: 6 × 10
caratcutcolorclaritydepthtablepricexyz
<dbl><ord><ord><ord><dbl><dbl><int><dbl><dbl><dbl>
0.23Ideal ESI2 61.5553263.953.982.43
0.21Premium ESI1 59.8613263.893.842.31
0.23Good EVS1 56.9653274.054.072.31
0.29Premium IVS2 62.4583344.204.232.63
0.31Good JSI2 63.3583354.344.352.75
0.24Very GoodJVVS262.8573363.943.962.48
# if only the dataset is known. 只显示数据
ggplot(diamonds)

png

# if only X-axis is known. The Y-axis can be specified in respective geoms.
# 只设定x轴,y轴数据可以在geoms中指定
ggplot(diamonds, aes(x=carat))  

png

# if both X and Y axes are fixed for all layers.
# 指定x轴和y轴
ggplot(diamonds, aes(x=carat, y=price))  

png

# Each category of the 'cut' variable will now have a distinct color, once a geom is added.
# 指定颜色类别cut
ggplot(diamonds, aes(x=carat, color=cut)) 

png

aes代表美学。ggplot2还将图的X轴和Y轴以及颜色,大小,形状,填充等也视为美观特征。如果要固定颜色,大小等(即,不根据数据框中的变量而变化) ,您需要aes()像这样在之外指定它。有关更多颜色,请参见R语言调色板。

ggplot(diamonds, aes(x=carat), color="steelblue")

png

2. 图层 The Layers

ggplot2中的图层也称为“ geoms ”。基本设置完成后,您可以将几何图形一个附加在另一个图形之上。此文档提供了所有可用geoms的全面列表。

ggplot(diamonds, aes(x=carat, y=price, color=cut)) + 
# Adding scatterplot geom (layer1) 添加散点图
geom_point() + 
# Adding moothing geom (layer2) 在散点图的基础上添加一条平滑的趋势曲线
geom_smooth() 
`geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'

png

我们在上图添加了两层(geom)- geom_point()和geom_smooth()。由于X轴Y轴和颜色是在ggplot()设置本身中定义的,因此这两层继承了那些美学。另外,您也可以如下所示在geom图层内指定这些外观

 # Same as above but specifying the aesthetics inside the geoms. 类似上面的结果
ggplot(diamonds) + 
geom_point(aes(x=carat, y=price, color=cut)) + 
geom_smooth(aes(x=carat, y=price, color=cut))
`geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'

png

注意X和Y轴,以及点的颜色如何根据cut变量的值而变化。图例已自动添加。我想提出一个改变。cut我不想在每个级别上使用多条平滑线,而是将它们全部集成在一条线下。怎么做?color从geom_smooth()层次上消除美学将达到目的。

library(ggplot2)
ggplot(diamonds) + 
geom_point(aes(x=carat, y=price, color=cut)) + 
# Remove color from geom_smooth 只画一条拟合平滑线
geom_smooth(aes(x=carat, y=price)) 
`geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'

png

 # same but simpler 类似上图同样的功能
ggplot(diamonds, aes(x=carat, y=price)) + 
geom_point(aes(color=cut)) + 
geom_smooth() 
`geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'

png

这对您来说是一个快速的挑战。可以使点的形状随color功能而变化吗?尽管设置过程花费了我们很多代码,但是增加诸如图层,每个cut的不同颜色等的复杂性却很容易。想象一下,如果要在基本图形中进行编写,必须编写多少代码?感谢ggplot2!

# Answer to the challenge 设置形状点
ggplot(diamonds, aes(x=carat, y=price, color=cut, shape=color)) + 
geom_point()
Warning message:
"Using shapes for an ordinal variable is not advised"
Warning message:
"The shape palette can deal with a maximum of 6 discrete values because
more than 6 becomes difficult to discriminate; you have 7. Consider
specifying shapes manually if you must have them."
Warning message:
"Removed 2808 rows containing missing values (geom_point)."

png

3. 标签 The Labels

现在,您已经绘制了图形的主要部分。您可能要添加图解的主要标题,并可能更改X和Y轴标题。这可以通过labs用于指定标签的层来完成。但是,操纵标签的大小,颜色是本文第四部分“主题”的工作。

gg <- ggplot(diamonds, aes(x=carat, y=price, color=cut)) + 
geom_point() + 
# add axis lables and plot title 添加标签
labs(title="Scatterplot", x="Carat", y="Price")
print(gg)

png

图的主要标题已添加,并且X和Y轴标签大写。注意:如果要在函数内部显示ggplot,则需要显式保存它,然后使用进行打印print(gg),就像我们上面所做的那样。

4. 主题 The Theme

除了我们要增加标签的大小并更改图例标题以外,几乎所有内容都已设置。调整标签的大小可以在theme()函数中通过设置功能plot.title,axis.text.x和axis.text.y。需要在中指定它们element_text()。如果要删除其中任何一个,请将其设置为element_blank(),它将完全消失。
调整图例标题有些棘手。如果您的图例是某个color属性的图例,并且其根据因数而变化,则您需要设置scale_color_discrete()中的name,其中颜色部分属于color属性,而离散部分属于离散属性,因为图例是基于因数变量的。

gg1 <- gg + 
    theme(
    # 设置标题大小,face="bold"字体加粗
        plot.title=element_text(size=30, face="bold"), 
        axis.text.x=element_text(size=15),
        axis.text.y=element_text(size=15),
        axis.title.x=element_text(size=25),
        axis.title.y=element_text(size=25)) +
    # add title and axis text, change legend title.
    # 添加渐变色,并设置颜色条图例标题
    scale_color_discrete(name="Cut of diamonds")  
print(gg1)  # print the plot

png

如果图例显示基于因子变量的形状属性,则需要使用scale_shape_discrete(name=“legend title”)进行更改。如果它是一个连续变量,改用scale_shape_continuous(name=“legend title”)。如果您的图例基于fill连续变量的属性,使用scale_fill_continuous(name=“legend title”)。

5. 分面 The Facets

在上一张图表中,您在同一张图表中具有所有不同cut绘制值的散点图。如果您想要每张图表一个cut值呢?就需要用到分面功能

gg1 + facet_wrap( ~cut , ncol=3)

png

facet_wrap(formula)接受一个公式作为参数。右边的项目对应于列。左侧的项定义行。

# row: color, column: cut
gg1 + facet_wrap(color ~ cut)  

png

facet_wrap,X和Y轴的比例固定为默认容纳所有点。这将使属性的比较有意义,因为它们的规模相同。但是,可以通过设置参数scales=free使比例尺自由调整,使图表看起来分布更均匀

# row: color, column: cut
# gg1 + facet_wrap(color ~ cut, scales="free")

出于比较目的,您也可以使用facet_grid(formula)将所有图在一个网格中。注意,各个图的标题已消失,为绘图区域留出更多空间。

gg1 + facet_grid(color ~ cut) 

png

6. 常用函数 Commonly Used Features

主要内容如下:

  • 6.1 绘制时间序列图(使用ggfortify)
  • 6.2 在同一ggplot上绘制多个时间序列
  • 6.3 条形图
  • 6.4 自定义布局
  • 6.5 翻转坐标轴
  • 6.6 调整X和Y轴范围
  • 6.7 等坐标轴
  • 6.8 变更主题
  • 6.9 图例删除和更改位置
  • 6.10 网格线
  • 6.11 图边距和背景
  • 6.12 注释
  • 6.13 保存ggplot

6.1 绘制时间序列图(使用ggfortify)

ggfortify包使直接从时间序列对象绘制时间序列变得非常容易,而无需将其转换为数据帧。下面的示例一步绘制AirPassengers时间序列。在此处查看更多ggfortify的自动绘图选项以绘制时间序列。

# 载入库
library(ggfortify)
# 查看数据
AirPassengers
Warning message:
"package 'ggfortify' was built under R version 3.6.1"
A Time Series: 12 × 12
JanFebMarAprMayJunJulAugSepOctNovDec
1949112118132129121135148148136119104118
1950115126141135125149170170158133114140
1951145150178163172178199199184162146166
1952171180193181183218230242209191172194
1953196196236235229243264272237211180201
1954204188235227234264302293259229203229
1955242233267269270315364347312274237278
1956284277317313318374413405355306271306
1957315301356348355422465467404347305336
1958340318362348363435491505404359310337
1959360342406396420472548559463407362405
1960417391419461472535622606508461390432
autoplot(AirPassengers) + 
labs(title="AirPassengers")

png

6.2 在同一ggplot上绘制多个时间序列

绘制多个时间序列需要以数据文件格式拥有数据,其中一列是用于X轴的日期。

方法1:转换后,您只需要不断地将时间序列的多个层逐个添加。

# Approach 1:
data(economics, package="ggplot2")  # init data
economics <- data.frame(economics)  # convert to dataframe
# 展示数据
head(economics)

# 画图
ggplot(economics) + 
# 画线条
geom_line(aes(x=date, y=pce, color="pcs")) + 
geom_line(aes(x=date, y=unemploy, col="unemploy")) + 
# 设定颜色
scale_color_discrete(name="Legend") + 
labs(title="Economics")
A data.frame: 6 × 6
datepcepoppsavertuempmedunemploy
<date><dbl><dbl><dbl><dbl><dbl>
1967-07-01506.719871212.64.52944
1967-08-01509.819891112.64.72945
1967-09-01515.619911311.94.62958
1967-10-01512.219931112.94.93143
1967-11-01517.419949812.84.73066
1967-12-01525.119965711.84.83018

png

方法2:通过将id设置为date字段,使用reforme2::Melt融合数据帧。然后只需添加一条geom_线,并将颜色美学设置为variable(这是在融化过程中创建的)。

# Approach 2:
library(reshape2)
# 融合数据
df <- melt(economics[, c("date", "pce", "unemploy")], id="date")
head(df)

# 绘图
ggplot(df) + 
geom_line(aes(x=date, y=value, color=variable)) + 
labs(title="Economics")
Warning message:
"package 'reshape2' was built under R version 3.6.1"
A data.frame: 6 × 3
datevariablevalue
<date><fct><dbl>
1967-07-01pce506.7
1967-08-01pce509.8
1967-09-01pce515.6
1967-10-01pce512.2
1967-11-01pce517.4
1967-12-01pce525.1

png

ggplot2的缺点是不可能在同一图上获得多个Y轴。以相同的比例绘制多个时间序列会使序列中的几个看起来很小。一个替代方法是facet_wrap设置它scales=‘free’。

df <- melt(economics[, c("date", "pce", "unemploy", "psavert")], id="date")
ggplot(df) + 
geom_line(aes(x=date, y=value, color=variable)) +
facet_wrap( ~ variable, scales="free")

png

6.3 条形图

默认情况下,ggplot会制作一个“计数”条形图,这意味着它会计算x美学指定的项目的频率并对其进行绘制。使用这种格式,您无需指定Y学。但是,如果您要制作Y给出的绝对数的条形图,则需要stat="identity"在内进行设置geom_ba。

# 显示数据
head(mtcars)
plot1 <- ggplot(mtcars, aes(x=cyl)) + 
# 画柱状图
geom_bar() + 
# Y axis derived from counts of X item
labs(title="Frequency bar chart")  
print(plot1)
A data.frame: 6 × 11
mpgcyldisphpdratwtqsecvsamgearcarb
<dbl><dbl><dbl><dbl><dbl><dbl><dbl><dbl><dbl><dbl><dbl>
Mazda RX421.061601103.902.62016.460144
Mazda RX4 Wag21.061601103.902.87517.020144
Datsun 71022.84108 933.852.32018.611141
Hornet 4 Drive21.462581103.083.21519.441031
Hornet Sportabout18.783601753.153.44017.020032
Valiant18.162251052.763.46020.221031

png

df <- data.frame(var=c("a", "b", "c"), nums=c(1:3))
# 显示数据
df
# Y axis is explicit. 'stat=identit
# 显示y
plot2 <- ggplot(df, aes(x=var, y=nums)) + 
geom_bar(stat = "identity")
print(plot2)
A data.frame: 3 × 2
varnums
<fct><int>
a1
b2
c3

png

6.4 自定义布局

gridExtra软件包提供了在单个网格中配置多个ggplots的功能。

library(gridExtra)
# 分配图像
grid.arrange(plot1, plot2, ncol=2)

png

6.5 翻转坐标轴

df <- data.frame(var=c("a", "b", "c"), nums=c(1:3))
ggplot(df, aes(x=var, y=nums)) + 
geom_bar(stat = "identity") + 
# 翻转坐标轴
coord_flip() + 
labs(title="Coordinates are flipped")

png

6.6 调整X和Y轴范围

有3种方法可以更改X和Y轴范围:

  1. Using coord_cartesian(xlim=c(x1,x2))
  2. Using xlim(c(x1,x2))
  3. Using scale_x_continuous(limits=c(x1,x2))

第 2项和第3项将从数据本身中删除超出限制的数据点。因此,如果添加任何平滑线等,结果将失真。项目1(coord_cartesian)不会删除任何数据点,而是会放大到图表的特定区域。

ggplot(diamonds, aes(x=carat, y=price, color=cut)) + 
geom_point() + 
geom_smooth() + 
# 设置y轴范围
coord_cartesian(ylim=c(0, 10000)) + 
labs(title="Coord_cartesian zoomed in!")
`geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'

png

ggplot(diamonds, aes(x=carat, y=price, color=cut)) + 
geom_point() + 
geom_smooth() + 
# 设定范围
ylim(c(0, 10000)) + 
labs(title="Datapoints deleted: Note the change in smoothing lines!")
`geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'

Warning message:
"Removed 5222 rows containing non-finite values (stat_smooth)."
Warning message:
"Removed 5222 rows containing missing values (geom_point)."

png

6.7 等坐标轴

添加coord_equal()到ggplot会将X和Y轴的限制设置为相等。下面是一个无意义的示例

ggplot(diamonds, aes(x=price, y=price+runif(nrow(diamonds), 100, 10000), color=cut)) + 
geom_point() + 
geom_smooth() + 
coord_equal()
`geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'

png

6.8 变更主题

除了基本的ggplot2主题外,您还可以使用这些内置主题之一来更改绘图的外观。

  1. theme_gray()
  2. theme_bw()
  3. theme_linedraw()
  4. theme_light()
  5. theme_minimal()
  6. theme_classic()
  7. theme_void()

ggthemes软件包提供了模仿知名杂志和软件的其他ggplot主题。这是一个如何更改主题的示例。

ggplot(diamonds, aes(x=carat, y=price, color=cut)) + 
geom_point() + 
geom_smooth() +
# 更改主题
theme_bw() + 
labs(title="bw Theme")
`geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'

png

6.9 图例删除和更改位置

通过设置主题(legend.position=“none”),可以删除图例。通过将其设置为“顶部”,即主题(legend.position=“顶部”),可以在图像周围移动图例。通过将legend.position设置为绘图内部的坐标,可以将图例放置在绘图内部。legend.justification表示图例的锚点,即将放置在legend.position给定坐标上的点。

# 无图例
p1 <- ggplot(diamonds, aes(x=carat, y=price, color=cut)) + 
geom_point() + 
geom_smooth() + 
# 无图例
theme(legend.position="none") + 
labs(title="legend.position='none'")
p2 <- ggplot(diamonds, aes(x=carat, y=price, color=cut)) + 
geom_point() + 
geom_smooth() + 
# legend at top 设置图例在图形顶部
theme(legend.position="top") + 
labs(title="legend.position='top'")  
p3 <- ggplot(diamonds, aes(x=carat, y=price, color=cut)) + 
geom_point() + 
geom_smooth() + 
labs(title="legend.position='coords inside plot'") + 
# legend inside the plot 设置图形位置
theme(legend.justification=c(1,0), legend.position=c(1,0))  
# arrange统一显示图像
grid.arrange(p1, p2, p3, ncol=3)  
`geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'

`geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'

`geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'

png

6.10 网格线

ggplot(mtcars, aes(x=cyl)) + 
geom_bar(fill='darkgoldenrod2') +
theme(panel.background = element_rect(fill = 'steelblue'),
# 设置主网格线
panel.grid.major = element_line(colour = "firebrick", size=3),
panel.grid.minor = element_line(colour = "blue", size=1))

png

6.11 图边距和背景

ggplot(mtcars, aes(x=cyl)) + 
geom_bar(fill="firebrick") + 
# top, right, bottom, left
# plot.background设置背景,plot.margain设置边距
theme(plot.background=element_rect(fill="steelblue"), plot.margin = unit(c(2, 4, 1, 3), "cm")) 

png

6.12 注释

library(grid)
# 添加注释
my_grob = grobTree(textGrob("This text is at x=0.1 and y=0.9, relative!\n Anchor point is at 0,0", x=0.1,  y=0.9, hjust=0,
  gp=gpar(col="firebrick", fontsize=25, fontface="bold")))
ggplot(mtcars, aes(x=cyl)) + 
geom_bar() + 
annotation_custom(my_grob) + 
labs(title="Annotation Example")

png

6.13 保存ggplot

plot1 <- ggplot(mtcars, aes(x=cyl)) + 
geom_bar()
# 保存图像
ggsave("myggplot.png")  # saves the last plot.
ggsave("myggplot.png", plot=plot1)  # save a stored ggplot
Saving 6.67 x 6.67 in image

Saving 6.67 x 6.67 in image
  • 4
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值