Візуалізація даних у R за допомогою ggplot2

Тюторіал зі створення інтерактивних графіків (ggplot + plotly) — мінімум коду, максимум сенсу

Yurii K.

2025-10-20

Партнери







EU funded / House of Europe

План

  1. Якими бувають графіки?
  2. ggplot2 у 10 хв: ідея та синтаксис
  3. Покроково ускладнюємо графік
  4. Базові типи графіків (scatter/line/bar/hist/density/box/violin/area/tile)
  5. Facets, scales, coord, themes
  6. Інтерактивність із plotly (hover/zoom/pan/legend)
  7. Анімації (plotly frames) + огляд gganimate
  8. Корисні джерела

Якими бувають графіки?

Налаштування

library(ggplot2)
library(plotly)
library(dplyr)
library(tidyr)
library(gapminder)
library(gganimate)
library(DT)

theme_brand <- function() 
  theme_minimal(base_family="Arial") +
  theme(plot.title=element_text(face="bold", 
                                color="#3f5988", 
                                size=20),
        axis.title=element_text(color="#3f5988"),
        legend.position="bottom")

scale_color_brand <- scale_color_manual(
  values=c("#3f5988","#f56d40","#3c699b","#f6c5a0","#1b998b","#c44536"))

scale_fill_brand  <- scale_fill_manual(
  values=c("#3f5988","#f56d40","#3c699b","#f6c5a0","#1b998b","#c44536"))

Набори даних (gapminder)

head(gapminder)


Набори даних (economics)

head(economics)


Набори даних (mtcars)

head(mtcars)


Синтаксис ggplot2

ggplot(data, aes(x, y, color, fill, size, group)) +
    geom_*() +     # геометрична фігура об'єкта
    facet_*() +    # розбиття на панелі
    scale_*() +    # налаштування шкал (колір, розмір, осі)
    coord_*() +    # система координат
    theme_*()      # зовнішній вигляд, стиль

🔹 ggplot(data, aes(x, y, color, fill, size, group))

  • data — назва датафрейму, який використовується для побудови графіка.

  • aes() — функція для задання естетичних параметрів (відображення змінних на візуальні елементи графіка):

    • x — змінна по осі X.
    • y — змінна по осі Y.
    • color — колір об’єктів (ліній, точок тощо) в залежності від змінної.
    • fill — заповнення (наприклад, кольором) всередині об’єкта (бар, полігон).
    • size — розмір об’єктів (наприклад, точок).
    • group — групування даних для побудови зв’язаних ліній або інших графічних елементів.

🔹 geom_*()

Функція, яка визначає тип геометричного об’єкта для побудови графіка.

Приклади:

  • geom_point() — точкова діаграма (scatter plot).
  • geom_line() — лінійний графік.
  • geom_bar() — стовпчиковий графік.
  • geom_histogram() — гістограма.

Кожен geom_ відображає дані в різний спосіб.

🔹 facet_*()

Функції для розбиття графіка на кілька панелей за значеннями змінних.

Дозволяє зручно порівнювати підмножини даних.

Приклади:

  • facet_wrap(~var) — створює окрему панель для кожного рівня змінної var.
  • facet_grid(rows ~ cols) — створює панелі в сітці: рядки та стовпці за відповідними змінними.

🔹 scale_*()

Функції для налаштування шкал: кольорів, розмірів, осей тощо.

Дозволяє змінювати:

  • підписи
  • діапазони
  • кольорові палітри

Приклади:

  • scale_x_continuous() — налаштування шкали осі X.
  • scale_color_manual() — власні кольори для color.
  • scale_fill_brewer() — палітра кольорів з пакету RColorBrewer.

🔹 coord_*()

Функції, що визначають систему координат графіка.

Приклади:

  • coord_cartesian() — стандартна декартова система.
  • coord_flip() — змінює місцями осі X і Y.
  • coord_polar() — полярні координати (наприклад, для кругових діаграм).

🔹 theme_*()

Налаштування зовнішнього вигляду графіка.

Можна змінити:

  • шрифти
  • фони
  • кольори сітки
  • положення легенди

Приклади:

  • theme_minimal() — мінімалістичний стиль.
  • theme_classic() — класичний стиль.
  • theme() — детальне ручне налаштування елементів (наприклад, axis.text, legend.position тощо).

Перший графік: scatter

ggplot(gapminder, aes(gdpPercap, lifeExp)) +
  geom_point(size = 2) + 
  theme_brand()

Додаємо колір за групою

ggplot(gapminder, aes(gdpPercap, lifeExp, color = continent)) +
  geom_point(alpha=.7, size = 2) + 
  scale_color_brand + 
  theme_brand()

Розмір на основі даних про наслення

ggplot(gapminder, aes(gdpPercap, lifeExp, color=continent, size=pop)) +
  geom_point(alpha=.6) + 
  scale_color_brand + 
  theme_brand()

Вісь X (без кастомних labels)

ggplot(gapminder, aes(gdpPercap, lifeExp, color=continent)) +
  geom_point(alpha=.7, size = 2) +
  scale_x_log10() +
  scale_color_brand + 
  theme_brand()

Підписи даних

ggplot(gapminder, aes(gdpPercap, lifeExp, color=continent)) +
  geom_point(alpha=.7, size = 2) +scale_x_log10() +
  labs(title="Тривалість життя та дохід", subtitle="Колір — континент", 
        x="GDP per capita (log10)", y="Life expectancy") +
  scale_color_brand + theme_brand()

Facet-и

ggplot(gapminder, aes(gdpPercap, lifeExp, color=continent)) +
  geom_point(alpha=.6, size = 2) +
  scale_x_log10() +
  facet_wrap(~continent) +
  scale_color_brand + theme_brand()

Лінійний тренд (smooth)

ggplot(gapminder, aes(gdpPercap, lifeExp, color=continent)) +
  geom_point(alpha=.4, size = 2) + 
  geom_smooth(se=FALSE) +
  scale_x_log10() +
  scale_color_brand + theme_brand()

Лінійний графік (часовий ряд)

economics |>
  ggplot(aes(date, unemploy)) +
  geom_line() + 
  labs(title="Часовий ряд: безробіття") + 
  theme_brand()

Стовпці: скільки країн на континеті?

gapminder |> filter(year==2007) |>
  ggplot(aes(continent, fill=continent)) +
  geom_bar() + 
  scale_fill_brand + 
  theme_brand()

Гістограма

ggplot(gapminder, aes(lifeExp)) +
  geom_histogram(bins=30, 
                 fill="#3c699b", 
                 color="white") +
  theme_brand()

Щільність розподілу

ggplot(gapminder, aes(lifeExp, fill=continent)) +
  geom_density(alpha=.4) + 
  scale_fill_brand + 
  theme_brand()

Boxplot

gapminder |> filter(year==2007) |>
  ggplot(aes(continent, lifeExp, fill=continent)) +
  geom_boxplot(alpha=.7, outlier.color="#f56d40") +
  scale_fill_brand +
  theme_brand()

Violin

gapminder |> filter(year==2007) |>
  ggplot(aes(continent, lifeExp, fill=continent)) +
  geom_violin(alpha=.6, trim=TRUE) +
  scale_fill_brand +
  theme_brand()

Area

economics |>
  ggplot(aes(date, unemploy)) +
  geom_area(alpha=.6, fill="#3f5988") +
  theme_brand()

Heatmap / Tile

as.data.frame(as.table(cor(mtcars))) |>
  ggplot(aes(Var1, Var2, fill=Freq)) +
  geom_tile() + 
  scale_fill_gradient(low="#f6c5a0", 
                      high="#3f5988") +
  coord_equal() + 
  theme_brand() + 
  labs(fill="corr")

coord_flip (горизонтальні бари)

gapminder |> 
  filter(year==2007) |>
  slice(1:12*10) |>
  ggplot(aes(reorder(country, gdpPercap), gdpPercap, fill=continent)) +
  geom_col() + scale_y_log10() +
  coord_flip() + scale_fill_brand + 
  theme_brand() + labs(x=NULL, y="GDP per capita")

Частки категорій (донат)

gapminder |> filter(year==2007) |>
  count(continent) |>
  ggplot(aes(x=1, y=n, fill=continent)) +
  geom_col(width=.7, color="white") +
  coord_polar(theta="y") + 
  scale_fill_brand + theme_void() + theme_brand()

Встановлення кольорів

ggplot(mtcars, aes(hp, mpg, color=factor(cyl))) +
  geom_point(size=3) +
  scale_color_manual(values=c("4"="#1b998b","6"="#3c699b","8"="#f56d40")) +
  theme_brand()

Легенда: керування виглядом

ggplot(mpg, aes(displ, hwy, color=class)) +
  geom_point() + 
  guides(color=guide_legend(nrow=2, byrow=TRUE)) +
  theme_brand() + 
  theme(legend.position="bottom")

Анотації

ggplot(gapminder, aes(gdpPercap, lifeExp)) +
  geom_point(alpha=.5, size = 2) +
  annotate("text", x=1e4, y=80, label="⬅ якась подія", color="#f56d40", fontface="bold") +
  scale_x_log10() + 
  theme_brand()

Титри/пояснення (labs)

ggplot(mtcars, aes(hp, mpg)) +
  geom_point(size = 3) +
  labs(title="HP vs MPG", subtitle="Приклад підписів", caption="Джерело: mtcars") +
  theme_brand()

Теми: детальна стилізація

ggplot(mtcars, aes(hp, mpg)) + 
  geom_point(color="#3f5988") +
  theme_minimal() + 
  theme(plot.title=element_text(face="bold", 
                                size=18, 
                                color="#3f5988")) +
  labs(title="Кастомні елементи теми")

Демонстрація тем

ggplot(mtcars, aes(hp, mpg)) +
  geom_point(size = 3) +
  theme_minimal() 
ggplot(mtcars, aes(hp, mpg)) +
  geom_point(size = 3) +
  theme_grey() 
ggplot(mtcars, aes(hp, mpg)) +
  geom_point(size = 3) +
  theme_bw() 
ggplot(mtcars, aes(hp, mpg)) +
  geom_point(size = 3) +
  theme_linedraw() 
ggplot(mtcars, aes(hp, mpg)) +
  geom_point(size = 3) +
  theme_light() 
ggplot(mtcars, aes(hp, mpg)) +
  geom_point(size = 3) +
  theme_dark() 
ggplot(mtcars, aes(hp, mpg)) +
  geom_point(size = 3) +
  theme_classic() 

Інтерактивність: ховери (text)

g22 <- gapminder |> filter(year==2007) |>
  ggplot(aes(gdpPercap, lifeExp, color=continent,
             text=paste(country, "<br>GDP:", round(gdpPercap), "<br>LE:", lifeExp))) +
  geom_point(size=3, alpha=.85) + scale_x_log10() +
  scale_color_brand + theme_brand()
plotly::ggplotly(g22)

Анімація

p_anim <- gapminder |>
  slice(1:(12*12)) |>
  ggplot(aes(
    x=reorder(country, gdpPercap), 
    y=gdpPercap, 
    fill=continent)) +
  geom_col() + 
  coord_flip() + 
  scale_y_log10() +
  scale_fill_brand + 
  theme_brand() +
  transition_states(year, 
                    wrap=FALSE, 
                    transition_length=5, 
                    state_length=1)

animate(p_anim, 
        nframes=120, 
        fps=20, 
        width=900, 
        height=600, 
        renderer=gifski_renderer("gdp.gif"))  

Анімація (приклад)

Анімація

p <- ggplot(gapminder, 
  aes(gdpPercap, 
      lifeExp, 
      size = pop, 
      color = continent)) +
  geom_point(alpha = 0.7) +
  scale_color_viridis_d() +
  scale_size(range = c(2, 12)) +
  scale_x_log10() +
  labs(
    title = "Year: {frame_time}",
    x = "GDP per capita",
    y = "Life expectancy"
  ) +
  transition_time(year) +
  ease_aes("linear")

animate(p, nframes=120, fps=20, 
  width=900, height=600, 
  renderer=gifski_renderer("img/animation2.gif"))

Анімація (приклад)

Додаткові матеріали

  • https://posit.co/wp-content/uploads/2022/10/data-visualization-1.pdf
  • https://r-charts.com/
  • https://r-graph-gallery.com/

Джерела

  • Hadley Wickham. ggplot2: Elegant Graphics for Data Analysis (Springer, 2nd ed.).
  • Michael Friendly. R Graphics / ggplot2 (слайди).
  • Christopher D. DeSante. A Short Guide to ggplot2.
  • Catherine Barber. Visualizing Data with ggplot2 in R.
  • RStudio Cheat Sheets: Data Visualization with ggplot2; Data Transformation with dplyr.

Дякую! 🙌

Питання? Пропозиції? Ідеї?