Диаграмма рассеяния в R с использованием ggplot2 и примером.
⚡ Умное резюме
Scatter Plot in R using ggplot2 maps two continuous variables to the x and y axes with geom_point(). This walkthrough covers grouping by colour, log transformations, fitted regression lines, labels, faceting, overplotting fixes, scales, themes, and saving.

Why Graphs Matter in Data Analysis
Графики — это третья часть процесса анализа данных. Первая часть посвящена данные extracпроизводство, вторая часть посвящена очистка и манипулирование данными. Наконец, специалисту по данным, возможно, придется представить свои результаты графически.
The workflow of a data scientist is summarised in the picture below.
- Первая задача специалиста по данным — определить вопрос исследования. Данный исследовательский вопрос зависит от целей и задач проекта.
- После этого одной из наиболее важных задач является разработка функций. Специалисту по данным необходимо собирать, манипулировать и очищать данные.
- Когда этот шаг будет завершен, он сможет приступить к исследованию набора данных. Иногда необходимо уточнить и изменить исходную гипотезу в связи с новым открытием.
- Когда пояснительная анализ достигнут, специалист по данным должен учитывать способность читателя понять основные концепции и модели.
- Его результаты должны быть представлены в формате, понятном всем заинтересованным сторонам. Один из лучших способов общаться результаты через график.
- Графики — невероятный инструмент для упрощения сложного анализа.
The rest of this tutorial builds those graphs with the ggplot2 package.
The ggplot2 Package
This tutorial focuses on building charts in R with ggplot2.
In this tutorial, you are going to use ggplot2 package. The package implements the Grammar of Graphics described by Leland Wilkinson in 2005. ggplot2 is flexible, ships with many themes, and lets you specify a plot at a high level of abstraction. Note that it does not produce three-dimensional or interactive graphics; those require packages such as plotly or rgl.
В ggplot2 график состоит из следующих аргументов:
- данным
- эстетическая картаping
- геометрический объект
- статистические преобразования
- Весы
- система координат
- корректировка положения
- огранка
В этом уроке вы узнаете, как контролировать эти аргументы.
Основной синтаксис 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()`
How to Create a Scatter Plot in R
Давайте посмотрим, как ggplot работает с набором данных mtcars. Вы начинаете с построения диаграммы рассеяния переменных mpg и drat.
Базовый график рассеяния
library(ggplot2) ggplot(mtcars, aes(x = drat, y = mpg)) + geom_point()
Code объяснение
- Сначала вы передаете набор данных mtcars в ggplot.
- Внутри аргумента aes() вы добавляете оси X и Y.
- Знак + означает, что вы хотите, чтобы R продолжал читать код. Это делает код более читабельным, если его взломать.
- Используйте geom_point() для геометрического объекта.
Выход:
График рассеяния с группами
Иногда может быть интересно различать значения по группе данных (т. е. данных на уровне факторов).
ggplot(mtcars, aes(x = mpg, y = drat)) + geom_point(aes(color = factor(gear)))
Code объяснение
- The aes() inside geom_point() controls the colour of each group. The grouping variable must be a factor, so gear is wrapped in factor().
- В целом у вас есть код aes(color = Factor(gear)), который меняет цвет точек.
Выход:
Change the Axis Scale with a Log Transformation
Rescaling data is a large part of the analyst job, because raw variables rarely arrive in a neat bell shape. Taking logarithms is one way to compress extreme values and make the plot less sensitive to outliers.
ggplot(mtcars, aes(x = log(mpg), y = log(drat))) + geom_point(aes(color = factor(gear)))
Code объяснение
- Вы преобразуете переменные x и y в функции log() непосредственно внутри функции aes() map.ping.
Обратите внимание, что можно применить любое другое преобразование, например стандартизацию или нормализацию.
Выход:
Диаграмма рассеяния с подобранными значениями
You can add another level of information to the graph. You can overlay the fitted values of a линейная регрессия.
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
Code объяснение
- my_graph: the plot is stored in the object my_graph, so later steps can add layers without repeating the whole call
- Аргумент stat_smooth() управляет методом сглаживания.
- метод = «lm»: линейная регрессия
- col = “#C42126”: Code для красного цвета линии
- se = FALSE: не отображать стандартную ошибку.
- size = 1: the thickness of the line. In ggplot2 3.4.0 and later this argument was renamed linewidth for line geometries.
Выход:
Обратите внимание, что доступны и другие методы сглаживания.
- GLM
- гам
- loess: the default for fewer than 1,000 observations
- rlm: robust linear model, from the MASS package
Before styling the chart, it is worth knowing when a scatter plot is the right choice at all.
Scatter Plot vs Line Chart vs Bubble Chart in R
All three plot two continuous variables against each other, so the choice comes down to what the reader should take away.
| Критерии | Точечная диаграмма | График линия | Bubblэлектронная диаграмма |
|---|---|---|---|
| Шоу | Корреляция между двумя переменными | Change of one variable over an ordered axis | Correlation plus a third magnitude |
| Ось X | Any continuous variable | Usually time or another ordered scale | Any continuous variable |
| Point order | Ненужные | Critical, points are connected | Ненужные |
| Third variable | Through colour or shape | Through separate lines | Through point size |
| ggplot2 call | geom_point() | geom_line() | geom_point(aes(size = z)) |
Connecting scatter points with a line when the x-axis has no natural order is a common mistake: it implies a sequence that does not exist. Reserve geom_line() for ordered axes such as dates. For distributions of a single variable, use a сюжет .
Добавьте информацию в график
So far the graphs carry no explanatory text. A reader should be able to see the story in the data from the chart alone, without consulting extra documentation, which means the chart needs good labels. You can add labels with the labs() function.
The basic syntax for labs() is:
labs(title = "Hello Guru99") arguments: - title: Main title displayed above the plot - subtitle: Secondary line below the title - caption: Note below the plot, usually the data source - x: Rename the x-axis - y: Rename the y-axis - color / fill: Rename the legend Example: labs(title = "Hello Guru99", subtitle = "My first plot")
Добавить заголовок
Очевидно, что одна обязательная информация, которую следует добавить, — это заголовок.
my_graph +
labs(
title = "Plot Mile per hours and drat, in log"
)
Code объяснение
- my_graph: вы используете сохраненный график. Это позволяет избежать переписывания всех кодов каждый раз, когда вы добавляете новую информацию в график.
- You wrap the title inside labs().
Выход:
Добавить заголовок с динамическим именем
Динамический заголовок полезен для добавления более точной информации в заголовок.
Вы можете использовать функцию 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"
Вы можете добавить к нашему графику динамическое имя, а именно: среднее значение расхода миль на галлон.
mean_mpg <- mean(mtcars$mpg) my_graph + labs( title = paste("Plot Mile per hours and drat, in log. Average mpg is", mean_mpg) )
Code объяснение
- Вы создаете среднее значение миль на галлон, используя среднее значение (mtcars$mpg), хранящееся в переменнойmean_mpg.
- Вы используете метод Paste() с помощью функции «Mean_mpg», чтобы создать динамический заголовок, возвращающий среднее значение миль на галлон.
Выход:
Добавить подзаголовок
Two further details make the graph more explicit. You are talking about the subtitle and the caption. The subtitle goes right below the title. The caption can inform about who did the computation and the source of the data.
my_graph +
labs(
title =
"Relation between Mile per hours and drat",
subtitle =
"Relationship break down by gear class",
caption = "Authors own computation"
)
Code объяснение
- Inside labs(), you added:
- title = «Связь между милями в час и дратом»: Добавить заголовок
- subtitle = «Отношения по классам снаряжения»: Добавить подзаголовок
- caption = «Вычисления принадлежат авторам: Добавить подпись»
- Каждую новую информацию вы отделяете запятой, ,
- Обратите внимание, что вы нарушаете строки кода. Это не является обязательным и лишь помогает легче читать код.
Выход:
Переименуйте оси X и Y.
Column names are rarely presentation-ready. They are often abbreviated or use underscores between words, as in GDP_CAP. Rename them on the plot and add units where they matter.
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"
)
Code объяснение
- Inside labs(), you added:
- x = «Определение проекта»: измените имя оси X.
- y = «Миль в час»: измените имя оси 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`
For instance, a range from 0 to 12 with a step of 4 returns four numbers: 0, 4, 8 and 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"
)
Code объяснение
- Функция Scale_y_continious() управляет оси
- Функция Scale_x_continious() управляет Ось х.
- Параметр Breaks управляет разделением оси. Вы можете добавить последовательность чисел вручную или использовать функцию seq():
- seq(1, 3.6, by = 0.2): Create the sequence from 1 to 3.6 in steps of 0.2, that is 14 break points
- seq(1, 1.6, by = 0.1): Create seven numbers from 1 to 1.6 in steps of 0.1
Выход:
Варианты
Finally, ggplot2 lets you restyle the whole plot with a single theme function. Eight complete themes ship with the package:
- theme_bw()
- theme_light()
- theme_classic()
- theme_linedraw()
- theme_dark()
- theme_minimal()
- theme_gray()
- 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"
)
Выход:
Сохранить графики
After all these steps, it is time to save and share your graph. Call ggsave(“name_of_the_file.png”) straight after plotting and the image is written to disk.
График сохраняется в рабочем каталоге. Чтобы проверить рабочий каталог, вы можете запустить этот код:
directory <- getwd() directory
Plot the finished graph, save it, and check where it landed:
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)
How to Create Faceted Scatter Plots in R with facet_wrap()
Faceting is one of the eight ggplot2 components listed earlier, and it is the cleanest answer to a crowded chart. Instead of squeezing every group into one panel, ggplot2 draws a small multiple for each level of a variable, all on the same scales so the panels stay comparable.
# One panel per gear count ggplot(mtcars, aes(x = drat, y = mpg)) + geom_point() + facet_wrap(~ gear) + theme_classic()
Three arguments do most of the work.
- нкол or Nrow: force the panels into a given layout, for example facet_wrap(~ gear, ncol = 2).
- Весы: “fixed” by default so every panel shares one axis range. Use “free_y” or “free” when the groups differ wildly in magnitude, but be aware that free scales make visual comparison between panels misleading.
- этикетировочные: replaces the raw factor level in each strip, for example labeller = label_both to print “gear: 4” instead of “4”.
Two grouping переменные. Use facet_grid() to build a matrix of panels, with the first variable across rows and the second across columns:
ggplot(mtcars, aes(x = drat, y = mpg)) + geom_point(aes(color = factor(cyl))) + facet_grid(am ~ gear) + theme_classic()
Facets or colours? Colour works well up to about four groups on a chart with limited overlap. Beyond that, or whenever the groups overlap heavily, faceting is easier to read because each panel carries only its own points. You can combine both: facet by one variable and colour by another, as in the facet_grid() example above.
How to Handle Overplotting in R Scatter Plots
With a few dozen observations every point is visible. With thousands, markers stack on top of one another and the densest region simply reads as a solid blob. That is чрезмерное заговор, and ggplot2 offers four standard remedies.
1. Reduce opacity. The cheapest fix. Overlapping points darken naturally, so density becomes visible:
ggplot(diamonds, aes(x = carat, y = price)) + geom_point(alpha = 0.05) + theme_classic()
2. Jitter discrete values. When a variable takes only a handful of values, points land on the same coordinates. A small random displacement separates them:
ggplot(mtcars, aes(x = factor(cyl), y = mpg)) + geom_jitter(width = 0.15, height = 0) + theme_classic()
Set height = 0 so the y values, which carry the real information, are never altered.
3. Bin the plane. For large datasets, count observations per cell and map the count to colour. Hexagonal bins avoid the visual artefacts that square bins produce:
ggplot(diamonds, aes(x = carat, y = price)) + geom_hex(bins = 40) + theme_classic()
4. Draw density contours. Contour lines outline the regions where the observations concentrate, and they layer neatly over faded points:
ggplot(diamonds, aes(x = carat, y = price)) + geom_point(alpha = 0.05) + geom_density_2d(color = "#C42126") + theme_classic()
As a rule of thumb, alpha handles a few thousand points, hexagonal binning handles tens of thousands, and sampling the data with dplyr::slice_sample() is the pragmatic option beyond that.
Scatter Plot in R: Code Референции
The table below lists the ggplot2 call for each option covered above:
| Цель | Code |
|---|---|
| Базовый график рассеяния |
ggplot(df, aes(x = x1, y = y)) + geom_point() |
| Scatter plot with colour group |
ggplot(df, aes(x = x1, y = y)) + geom_point(aes(color = factor(x2))) |
| Добавить подобранные значения |
ggplot(df, aes(x = x1, y = y)) + geom_point() + stat_smooth(method = "lm") |
| Добавить заголовок |
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")) |
| Переименовать х |
ggplot(df, aes(x = x1, y = y)) + geom_point() + labs(x = "X1") |
| Переименовать y |
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() |
| Facet by a group |
ggplot(df, aes(x = x1, y = y)) + geom_point() + facet_wrap(~ x2) |
| Handle overplotting |
ggplot(df, aes(x = x1, y = y)) + geom_point(alpha = 0.3) |
| Сохранено |
ggsave("my_fantastic_plot.png")
|












