Цель: освоить построение основных видов графиков в ggplot2 (scatter, line, histogram, boxplot, bar, violin, smooth, facets), а также базовые приёмы оформления: подписи, легенды, темы и цветовые шкалы.
0. Подготовка окружения
# install.packages(c("ggplot2", "dplyr", "tibble"))
library (ggplot2)
library (dplyr)
Attaching package: 'dplyr'
The following objects are masked from 'package:stats':
filter, lag
The following objects are masked from 'package:base':
intersect, setdiff, setequal, union
1. Теоретический минимум
1.1. Grammar of Graphics
График = данные → aes() → геометрия → фасетки → оформление.
# шаблон
# ggplot(data, aes(x=..., y=..., color=..., fill=..., shape=...)) +
# geom_*() + facet_*() + scale_*() + theme_minimal() +
# labs(title="...", x="...", y="...", color="...", fill="...")
1.2. Частые геометрии и оформление
geom_point, geom_line, geom_histogram, geom_boxplot, geom_violin, geom_bar/geom_col, geom_smooth(method=“lm”)
Темы: theme_minimal/bw/classic/light/dark; Шкалы: scale_brewer(), scale _manual()
2. Демонстрация на mtcars
data (mtcars); mtcars <- tibble:: rownames_to_column (mtcars, "model" ); head (mtcars,5 )
model mpg cyl disp hp drat wt qsec vs am gear carb
1 Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
2 Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
3 Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
4 Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
5 Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
2.1. Scatter
ggplot (mtcars, aes (wt, mpg, color= factor (cyl))) +
geom_point (size= 3 ) +
labs (title= "MPG vs Вес" , x= "Вес (1000 фунтов)" , y= "MPG" , color= "Цилиндры" ) +
theme_minimal ()
2.2. Line
ggplot (mtcars, aes (wt, mpg)) +
geom_line (color= "steelblue" , linewidth= 0.8 ) +
geom_point (color= "orange" , size= 2 ) +
labs (title= "Пример линейного графика" , x= "Вес" , y= "MPG" ) +
theme_light ()
2.3. Histogram
ggplot (mtcars, aes (mpg)) +
geom_histogram (bins= 10 , fill= "steelblue" , color= "white" ) +
labs (title= "Распределение MPG" , x= "MPG" , y= "Частота" ) +
theme_classic ()
2.4. Boxplot
ggplot (mtcars, aes (factor (cyl), mpg, fill= factor (cyl))) +
geom_boxplot (alpha= 0.9 ) +
labs (title= "MPG по числу цилиндров" , x= "Цилиндры" , y= "MPG" , fill= "Цилиндры" ) +
theme_minimal ()
2.5. Bar (подсчёт)
ggplot (mtcars, aes (factor (gear), fill= factor (carb))) +
geom_bar (position= "dodge" ) +
labs (title= "Количество авто по передачам и карбюраторам" , x= "Передачи" , fill= "Карбюраторы" ) +
theme_bw ()
2.6. Линия тренда (lm)
ggplot (mtcars, aes (wt, mpg)) +
geom_point (color= "steelblue" ) +
geom_smooth (method= "lm" , se= TRUE , color= "darkred" ) +
labs (title= "Линейная зависимость MPG от веса" , x= "Вес" , y= "MPG" ) +
theme_light ()
`geom_smooth()` using formula = 'y ~ x'
3. Практическая часть: новый датасет
set.seed (42 ); n <- 80
df <- data.frame (
age = sample (18 : 70 , n, replace= TRUE ),
weight = rnorm (n, 70 , 12 ),
height = rnorm (n, 170 , 10 ),
gender = sample (c ("Male" ,"Female" ), n, replace= TRUE ),
sport = sample (c ("Yes" ,"No" ), n, replace= TRUE )
) |> mutate (BMI = weight/ (height/ 100 )^ 2 )
head (df,8 )
age weight height gender sport BMI
1 66 53.58063 169.9818 Female No 18.54399
2 54 75.19382 165.7174 Male No 27.38078
3 18 60.26328 163.8633 Female No 22.44344
4 42 87.32922 149.7532 Male Yes 38.94101
5 27 64.82265 157.7525 Male No 26.04799
6 53 77.86777 171.7952 Female Yes 26.38371
7 35 73.86310 175.6762 Female No 23.93325
8 66 60.59393 165.0712 Male No 22.23752
4. Задания
A. Распределение
1) Гистограмма BMI по gender (fill=gender, position=“identity”, alpha).
2) Добавьте geom_density() поверх.
B. Взаимосвязь
3) Scatter age vs BMI, color=gender, shape=sport.
4) Добавьте geom_smooth(method=“lm”).
C. Сравнение групп
5) Boxplot BMI по gender.
6) Violin height по gender + stat_summary(median).
D. Средние по группам
7) Средний BMI по gender×sport (group_by + summarise).
8) Barplot результатов (position=“dodge”).
E. Дополнительно
9) Любой график с facet_wrap(~sport).
10) Свои цвета (scale_manual) и тема (theme ).
5. Контрольные вопросы
Что такое Grammar of Graphics?
Разница geom_bar vs geom_col?
Для чего color и fill?
Как добавить линию тренда и что даёт method=“lm”?
Зачем facet_wrap?
Почему важен factor? 7) Чем отличаются темы theme_*?