使用 ggplot2 在 R 中绘制散点图(附示例)

图表是数据分析过程的第三部分。第一部分是关于 数据提取第二部分涉及 清理和处理数据最后,数据科学家可能需要 以图表的方式传达他的结果.

数据科学家的工作可以通过下图来回顾

  • 数据科学家的首要任务是确定研究问题。该研究问题取决于项目的目的和目标。
  • 之后,最突出的任务之一就是特征工程。数据科学家需要收集、操作和清理数据
  • 当这个步骤完成后,他就可以开始探索数据集了。有时,需要根据新的发现来完善和改变原来的假设。

R 中的散点图

  • 当。。。的时候 解释性的 分析完成后,数据科学家必须考虑读者的 理解底层概念和模型.
  • 他的结果应该以所有利益相关者都能理解的格式呈现。最好的方法之一是 通信 结果是通过 图形.
  • 图表是简化复杂分析的绝佳工具。

ggplot2 包

本教程的这一部分重点介绍如何使用 R 制作图形/图表。

在本教程中,您将使用 ggplot2 包。该包建立在 Wilkinson 于 2005 年编写的《图形语法》一书的一致基础之上。ggplot2 非常灵活,融合了许多主题,并在高抽象级别上绘制了绘图规范。使用 ggplot2,您无法绘制三维图形和创建交互式图形。

在 ggplot2 中,图形由以下参数组成:

  • data
  • 审美映射
  • 几何对象
  • 统计变换
  • 坐标系
  • 职位调整
  • 刻面

您将在本教程中学习如何控制这些参数。

ggplot2的基本语法是:

ggplot(data, mapping=aes()) +
geometric object 

arguments: 
data: Dataset used to plot the graph
mapping: Control the x and y-axis 
geometric object: The type of plot you want to show. The most common object are:
 
- Point: `geom_point()` 
- Bar: `geom_bar()`
- Line: `geom_line()` 
- Histogram: `geom_histogram()`

散点图

让我们看看 ggplot 如何与 mtcars 数据集配合使用。首先绘制 mpg 变量和 drat 变量的散点图。

基本散点图

library(ggplot2)
ggplot(mtcars, aes(x = drat, y = mpg)) +
    geom_point()

代码说明

  • 首先将数据集 mtcars 传递给 ggplot。
  • 在 aes() 参数中,添加 x 轴和 y 轴。
  • + 号表示您希望 R 继续阅读代码。通过拆分代码,可以提高代码的可读性。
  • 使用 geom_point() 获取几何对象。

输出:

基本散点图

带组的散点图

有时,用一组数据(即因子级数据)来区分值可能会很有趣。

ggplot(mtcars, aes(x = mpg, y = drat)) +
    geom_point(aes(color = factor(gear)))

代码说明

  • geom_point() 中的 aes() 控制组的颜色。组应该是一个因子变量。因此,你将变量 gear 转换为因子。
  • 总之,您有代码 aes(color = factor(gear)) 来改变点的颜色。

输出:

带组的散点图

更改轴

重新调整数据比例是数据科学家工作的一个重要部分。极少数情况下,数据会呈现出漂亮的钟形。让数据对异常值不那么敏感的一个解决方案是重新调整它们的比例。

ggplot(mtcars, aes(x = log(mpg), y = log(drat))) +
    geom_point(aes(color = factor(gear)))

代码说明

  • 您直接在 aes() 映射内部转换 log() 中的 x 和 y 变量。

请注意,可以应用任何其他转换,例如标准化或规范化。

输出:

改变轴

带拟合值的散点图

您可以向图表添加另一层信息。您可以绘制线性回归的拟合值。

my_graph <- ggplot(mtcars, aes(x = log(mpg), y = log(drat))) +
    geom_point(aes(color = factor(gear))) +
    stat_smooth(method = "lm",
        col = "#C42126",
        se = FALSE,
        size = 1)
my_graph

代码说明

  • graph:将图形存储到变量 graph 中。这有助于进一步使用或避免代码太复杂
  • 参数 stat_smooth() 控制平滑方法
  • 方法 = “lm”:线性回归
  • col = “#C42126”:线条红色的代码
  • se = FALSE:不显示标准错误
  • size = 1:行的大小为 1

输出:

带拟合值的散点图

请注意,还有其他平滑方法可用

  • m
  • GAM
  • loess:默认值

向图表添加信息

到目前为止,我们还没有在图表中添加信息。图表需要提供信息。读者只需查看图表即可了解数据分析背后的故事,而无需参考其他文档。因此,图表需要好的标签。您可以使用 labs() 函数添加标签。

lab() 的基本语法是:

lab(title = "Hello Guru99")
argument:
- title: Control the title. It is possible to change or add title with:			
- subtitle: Add subtitle below title			
- caption: Add caption below the graph			
- x: rename x-axis			
- y: rename y-axis			
Example:lab(title = "Hello Guru99", subtitle = "My first plot")	

添加标题

必须添加的信息显然是标题。

my_graph +
    labs(
        title = "Plot Mile per hours and drat, in log"
         )

代码说明

  • my_graph:使用您存储的图表。这样可以避免每次向图表添加新信息时重写所有代码。
  • 将标题包装在实验室 () 内。
  • 线条红色的代码
  • se = FALSE:不显示标准错误
  • size = 1:行的大小为 1

输出:

添加标题

添加具有动态名称的标题

动态标题有助于在标题中添加更精确的信息。

您可以使用 paste() 函数打印静态文本和动态文本。paste() 的基本语法是:

paste("This is a text", A)
arguments
- " ": Text inside the quotation marks are the static text
- A: Display the variable stored in A
- Note you can add as much static text and variable as you want. You need to separate them with a comma	

示例:

A <-2010
paste("The first year is", A)

输出:

## [1] "The first year is 2010"
B <-2018

paste("The first year is", A, "and the last year is", B)

输出:

## [1] "The first year is 2010 and the last year is 2018"

您可以为我们的图表添加一个动态名称,即mpg的平均值。

mean_mpg <- mean(mtcars$mpg)
my_graph + labs(
    title = paste("Plot Mile per hours and drat, in log. Average mpg is", mean_mpg)
)

代码说明

  • 你可以使用存储在 mean_mpg 变量中的 mean(mtcars$mpg) 创建 mpg 的平均值
  • 您可以使用 paste() 和 mean_mpg 来创建一个动态标题,返回 mpg 的平均值

输出:

添加具有动态名称的标题

添加字幕

另外两个细节可以使您的图表更加清晰。您正在讨论副标题和说明文字。副标题位于标题正下方。说明文字可以告知谁进行了计算以及数据来源。

my_graph +
    labs(
        title =
        "Relation between Mile per hours and drat",
        subtitle =
        "Relationship break down by gear class",
        caption = "Authors own computation"
    )

代码说明

  • 在实验室()中,你添加了:
    • title = “每小时英里和 drat 之间的关系”: 添加标题
    • subtitle = “按装备等级划分关系”:添加副标题
    • caption = “作者自己的计算:添加标题
    • 用逗号分隔每个新信息,,
  • 请注意,请拆分代码行。这不是强制性的,它只会帮助更轻松地阅读代码

输出:

添加字幕

重命名 x 轴和 y 轴

数据集中的变量本身可能并不总是明确的,或者按照惯例在有多个单词时使用 _(例如 GDP_CAP)。您不希望这样的名称出现在您的图表中。更改名称或添加更多详细信息(如单位)很重要。

my_graph +
    labs(
        x = "Drat definition",
        y = "Mile per hours",
        color = "Gear",
        title = "Relation between Mile per hours and drat",
        subtitle = "Relationship break down by gear class",
        caption = "Authors own computation"
    )

代码说明

  • 在实验室()中,你添加了:
    • x = “Drat definition”:更改 x 轴的名称
    • y =“英里每小时”:更改 y 轴的名称

输出:

重命名 x 轴和 y 轴

控制规模

您可以控制轴的比例。

当你需要创建一个数字序列时,函数 seq() 很方便。基本语法是:

seq(begin, last, by = x)
arguments:
- begin: First number of the sequence
- last: Last number of the sequence
- by= x: The step. For instance, if x is 2, the code adds 2 to `begin-1` until it reaches `last`	

例如,如果你想创建一个从 0 到 12 的范围,步长为 3,那么你将有四个数字,即 0 4 8 12

seq(0, 12,4)

输出:

## [1]  0  4  8 12

您可以按如下方式控制 x 轴和 y 轴的比例

my_graph +
    scale_x_continuous(breaks = seq(1, 3.6, by = 0.2)) +
    scale_y_continuous(breaks = seq(1, 1.6, by = 0.1)) +
    labs(
        x = "Drat definition",
        y = "Mile per hours",
        color = "Gear",
        title = "Relation between Mile per hours and drat",
        subtitle = "Relationship break down by gear class",
        caption = "Authors own computation"
    )

代码说明

  • 函数 scale_y_continuous() 控制 y轴
  • 函数 scale_x_continuous() 控制 x轴.
  • 参数 breaks 控制轴的分割,可以手动添加数字序列,也可以使用 seq() 函数:
    • seq(1, 3.6, by = 0.2):创建 2.4 个数字,范围从 3.4 到 3,步长为 XNUMX
    • seq(1, 1.6, by = 0.1):创建从 1 到 1.6 的七个数字,步长为 1

输出:

控制规模

主题

最后,R 允许我们使用不同的主题来定制我们的图表。ggplot2 库包含八个主题:

  • theme_bw()
  • theme_light()
  • theme_classis()
  • 主题_线条绘制()
  • 主题暗()
  • 主题最小()
  • 主题灰色()
  • theme_void()
my_graph +
    theme_dark() +
    labs(
        x = "Drat definition, in log",
        y = "Mile per hours, in log",
        color = "Gear",
        title = "Relation between Mile per hours and drat",
        subtitle = "Relationship break down by gear class",
        caption = "Authors own computation"
    )

输出:

主题

保存地块

完成所有这些步骤后,就可以保存和共享您的图表了。绘制图表后立即添加 ggsave('NAME OF THE FILE),它将存储在硬盘上。

图表保存在工作目录中。要检查工作目录,可以运行以下代码:

directory <-getwd()
directory

让我们绘制您精彩的图表,保存并检查位置

my_graph +
    theme_dark() +
    labs(
        x = "Drat definition, in log",
        y = "Mile per hours, in log",
        color = "Gear",
        title = "Relation between Mile per hours and drat",
        subtitle = "Relationship break down by gear class",
        caption = "Authors own computation"
    )

输出:

保存地块

ggsave("my_fantastic_plot.png")

输出:

## Saving 5 x 4 in image

备注:仅出于教学目的,我们创建了一个名为 open_folder() 的函数来为您打开目录文件夹。您只需运行下面的代码并查看图片存储的位置。您应该看到一个名为 my_fantastic_plot.png 的文件。

# Run this code to create the
function
open_folder <- function(dir) {
    if (.Platform['OS.type'] == "windows") {
        shell.exec(dir)
    } else {
        system(paste(Sys.getenv("R_BROWSER"), dir))
    }
}

# Call the
function to open the folder open_folder(directory)

总结

您可以在下表中总结创建散点图的参数:

目的 代码
基本散点图
ggplot(df, aes(x = x1, y = y)) + geom_point()
带颜色组的散点图
ggplot(df, aes(x = x1, y = y)) + geom_point(aes(color = factor(x1)) + stat_smooth(method = "lm")
添加拟合值
ggplot(df, aes(x = x1, y = y)) + geom_point(aes(color = factor(x1))
添加标题
ggplot(df, aes(x = x1, y = y)) + geom_point() + labs(title = paste("Hello Guru99"))
添加字幕
ggplot(df, aes(x = x1, y = y)) + geom_point() + labs(subtitle = paste("Hello Guru99"))
重命名 x
ggplot(df, aes(x = x1, y = y)) + geom_point() + labs(x = "X1")
重命名
ggplot(df, aes(x = x1, y = y)) + geom_point() + labs(y = "y1")
控制规模
ggplot(df, aes(x = x1, y = y)) + geom_point() + scale_y_continuous(breaks = seq(10, 35, by = 10)) + scale_x_continuous(breaks = seq(2, 5, by = 1)
创建日志
ggplot(df, aes(x =log(x1), y = log(y))) + geom_point()
主题
ggplot(df, aes(x = x1, y = y)) + geom_point() + theme_classic()
已保存
ggsave("my_fantastic_plot.png")