class: center, middle, inverse, title-slide .title[ # Визуализация данных в R ] .subtitle[ ## base r, ggplot2, plotly etc.. ] .author[ ### Полина и Лена ] .date[ ### 2023/03/20 (updated: 2023-03-26) ] --- class: inverse, center, middle # baser r plots --- ### Важность визуализации .pull-left[ <img src="img/ex.jfif"> ] .pull-right[ <img src="img/dino.jfif"> ] --- ### Какие можно вспомнить виды графиков? -- - Диаграмма рассеяния (scatterplot) -- - Гистограмма (histogram) -- - Барплот (barplot) -- <br>**Чем барплот отличается от гистограммы?** -- <br>Гистограммы для непрерывных величин, а барплоты для категориальных. -- - Боксплот (boxplot) -- - Скрипичная диаграмма (violin plot) -- - Pie chart (не рекомендуется) -- - Диаграмма Венна -- - Heatmap, density plot, upset, flowchart и много чего еще… --- # mtcars Мы будем работать с датасетом `mtcars` (Motor Trend Car Road Tests) -- <br>Чтобы посмотреть описание датасета вобьем в консоль ```r ?mtcars ``` -- A data frame with 32 observations on 11 (numeric) variables. <br>[, 1] mpg Miles/(US) gallon <br>[, 2] cyl Number of cylinders <br>[, 3] disp Displacement (cu.in.) <br>[, 4] hp Gross horsepower <br>[, 5] drat Rear axle ratio <br>[, 6] wt Weight (1000 lbs) <br>[, 7] qsec 1/4 mile time <br>[, 8] vs Engine (0 = V-shaped, 1 = straight) <br>[, 9] am Transmission (0 = automatic, 1 = manual) <br>[,10] gear Number of forward gears <br>[,11] carb Number of carburetors --- # mtcars
--- # mtcars .left-column[ Чтобы посмотреть описательные статистики датасета наберем в консоли: ```r summary(mtcars) ``` <br> <br> <br> <br> <br> <br> <br> <br> <br> ] .right-column[ ``` ## mpg cyl disp hp ## Min. :10.40 Min. :4.000 Min. : 71.1 Min. : 52.0 ## 1st Qu.:15.43 1st Qu.:4.000 1st Qu.:120.8 1st Qu.: 96.5 ## Median :19.20 Median :6.000 Median :196.3 Median :123.0 ## Mean :20.09 Mean :6.188 Mean :230.7 Mean :146.7 ## 3rd Qu.:22.80 3rd Qu.:8.000 3rd Qu.:326.0 3rd Qu.:180.0 ## Max. :33.90 Max. :8.000 Max. :472.0 Max. :335.0 ## drat wt qsec vs ## Min. :2.760 Min. :1.513 Min. :14.50 Min. :0.0000 ## 1st Qu.:3.080 1st Qu.:2.581 1st Qu.:16.89 1st Qu.:0.0000 ## Median :3.695 Median :3.325 Median :17.71 Median :0.0000 ## Mean :3.597 Mean :3.217 Mean :17.85 Mean :0.4375 ## 3rd Qu.:3.920 3rd Qu.:3.610 3rd Qu.:18.90 3rd Qu.:1.0000 ## Max. :4.930 Max. :5.424 Max. :22.90 Max. :1.0000 ## am gear carb ## Min. :0.0000 Min. :3.000 Min. :1.000 ## 1st Qu.:0.0000 1st Qu.:3.000 1st Qu.:2.000 ## Median :0.0000 Median :4.000 Median :2.000 ## Mean :0.4062 Mean :3.688 Mean :2.812 ## 3rd Qu.:1.0000 3rd Qu.:4.000 3rd Qu.:4.000 ## Max. :1.0000 Max. :5.000 Max. :8.000 ``` ] --- # Диаграмма рассеяния (scatterplot) .pull-left[ ```r plot(mtcars$mpg) ``` <br>На диаграмме рассеяния каждому наблюдению соответствует точка, координаты которой равны значениям двух каких-то параметров этого наблюдения. <br> <br>mpg - расход топлива <br>**index** - порядок значений колонки mpg в таблице ] .pull-right[ <!-- --> ] --- # Scatterplots .pull-left[ ```r plot(x = mtcars$disp, y = mtcars$mpg) ``` равнозначные обозначения ```r plot(mtcars$disp ~ mtcars$mpg) ``` <br> <br>mpg - расход топлива (Miles/(US) gallon) <br>нарисуем зависимость mpg от displacement ] .pull-right[ <!-- --> ] --- # Scatterplots .pull-left[ ```r plot(mtcars$wt, * type="b") ``` аргумент **type =.** <br>type = "p", default <br>just lines (type = "l") <br>both points and lines connected (type = "b") <br>both points and lines with the lines running through the points (type = "o") <br>empty points joined by lines (type = "c") ] .pull-right[ <!-- --> ] --- # Histograms .pull-left[ <br>Позволяет быстро посмотреть на распределение своих данных ```r hist(mtcars$cyl) ``` <br> По оси **х** - частота или количество машин с конкретным количеством цилиндров (**cyl**) <br> наглядное представление функции плотности вероятности некоторой случайной величины, построенное по выборке ] .pull-right[ <!-- --> ] --- # Histograms .pull-left[ ```r hist(mtcars$wt, *main = "Title", ylab="y", xlab="x", *col="coral", border="blue") ``` ] .pull-right[ <!-- --> ] --- # Histograms .pull-left[ ```r hist(mtcars$wt, main = "Title", ylab="y", xlab="x", * col = rainbow(25), border="blue") ``` rainbow() автоматически применяет градиент от красного к зеленому ```r rainbow(5) ``` ``` ## [1] "#FF0000" "#CCFF00" "#00FF66" "#0066FF" "#CC00FF" ``` ] .pull-right[ <!-- --> ] --- # Histograms .pull-left[ ```r hist(mtcars$wt, main = "Title", ylab="y", xlab="x", * col = terrain.colors(12), border="blue") ``` Можно поэкспериментировать с числом, которое подается функции **terrain.colors()** ] .pull-right[ <!-- --> ] --- # Оффтопик .pull-left[ base r pallets ```r head(hcl.pals()) ``` ``` ## [1] "Pastel 1" "Dark 2" "Dark 3" "Set 2" "Set 3" "Warm" ``` пример использования ```r hist(mtcars$wt, main = "Title", ylab="y", xlab="x", * col = hcl.colors(20,"Pastel 1"), border="blue") ``` ] .pull-right[ <!-- --> <br>rainbow(n, s = 1, v = 1, start = 0, end = max(1, n - 1)/n, alpha, rev = FALSE) <br>heat.colors(n, alpha, rev = FALSE) <br>terrain.colors(n, alpha, rev = FALSE) <br>topo.colors(n, alpha, rev = FALSE) <br>cm.colors(n, alpha, rev = FALSE) <br>[Rcolor.pdf](http://www.stat.columbia.edu/~tzheng/files/Rcolor.pdf) ] --- # Histograms .pull-left[ ```r hist(mtcars$wt, main = "Title", ylab="y", xlab="x", col = terrain.colors(12), border="blue", * freq = FALSE) ``` По умолчанию по оси **у** отложена частота (frequency) <br>Если выставить freq = FALSE значение на оси **у** изменится на пллотность (density) <br>Данные разбиты на **bins**, каждый бин - интервал данных. ] .pull-right[ <!-- --> ] --- # Histograms .pull-left[ ```r hist(mtcars$wt, main = "Title", ylab="y", xlab="x", col = terrain.colors(12), border="blue", freq = FALSE) *lines(density(mtcars$wt)) ``` ] .pull-right[ <!-- --> ] --- # Boxplot .pull-left[ ```r boxplot(mtcars$mpg, ylab = "y") ``` график, использующийся в описательной статистике, компактно изображающий одномерное распределение вероятностей. <br> <br>Такой вид диаграммы в удобной форме показывает **медиану** (или, если нужно, среднее), нижний и верхний **квартили**, **минимальное** и **максимальное** значение выборки и **выбросы**. ] .pull-right[ <!-- --> ] --- # Boxplot .pull-left[ ```r boxplot(mtcars$mpg ~ mtcars$cyl, * main = "Title", * col="lightblue") ``` Дополнительная кастомизация ] .pull-right[ <!-- --> ] --- .pull-left[ ### Другие типы плотов в base r ```r par(mfrow=c(3, 1)) ### stripchart() stripchart(mtcars$mpg, main = "Mpg", method="jitter", col = "orange", pch=10) ### barplot() barplot(mtcars$mpg[1:6], main = "Первые 6 наблюдений расхода топлива", ylab = "Miles/(US) gallon", names.arg = row.names(mtcars)[1:6], col = terrain.colors(10) ) ### q-q plot qqnorm(mtcars$mpg, pch = 1, frame = FALSE) qqline(mtcars$mpg, col = "steelblue", lwd = 2) ``` Для дальнейшей кастомизации: [CheatSheet](https://r-graph-gallery.com/6-graph-parameters-reminder.html) ] .pull-right[ <!-- --> ] --- class: inverse, center, middle # ggplot2!! --- .pull-left[ ### Grammar of graphics <br> <br> <br>Подход к построению графиков в `ggplot2` принципиально отличается от обычных пакетов визуализации (matplotlib, seaborn в питоне). <br>Фишка `ggplot2` состоит в применении языка грамматики графики - набора правил для построения графиков. <br>Такой подход дает огромную гибкость и возможность создания и кастомизации практически любого графика. Пакет опирается на книгу The Grammar of Graphics (Leland Wilkinson). ] .pull-right[ <img src="img/gg.jfif"> ] --- class: fullscreen, top, center background-image: url("img/ggp.jfif") .right[https://twitter.com/tanya_shapiro/status/1576935152575340544] --- # ggplot2 <br>[ggplot2 tutorial](https://ggplot2.tidyverse.org) <br>Установка библиотеки: ```r install.packages("ggplot2") ``` `ggplot2` входит в core `tidyverse`, так что если вы уже установили `tidyverse` отдельно устанавливать `ggplot2` не надо --- # wc3_units
--- .pull-left[ ### ggplot() ```r *ggplot(data = wc3_units) ``` WarCraft3 dataset ] .pull-right[ ggplot() функции подается датафрейм <!-- --> ] --- .pull-left[ ### aes() ```r ggplot(data = wc3_units, * aes(x = race, y = hp)) ``` <br>aes = aesthetics <br>aes() отражает, какие переменные и как мы собираемся использовать в графике. Здесь мы прописали, что по X будет race, по Y hp. ] .pull-right[ <!-- --> ] --- .pull-left[ ### geom_() ```r ggplot(data = wc3_units, aes(x = race, y = hp)) + * geom_point() ``` geom = geometry ] .pull-right[ <!-- --> ] --- .pull-left[ ### aes() ```r ggplot(data = wc3_units, * aes(x = race, y = hp)) + geom_point() ``` Вернемся к aes() и рассмотрим подробнее ] .pull-right[ <!-- --> ] --- # ggplot aesthetics (параметры) <img src="img/aes.png"> --- .pull-left[ ### color ```r wc3_units %>% * ggplot(aes(race, hp, color = armor_type)) + geom_point() ``` ```r ?aes ``` ] .pull-right[ <!-- --> ] --- .pull-left[ ### geom aesthetics <br>aes() можно задавать как внутри ggplot(), так и внутри geoms <br>Например: <br>geom_point() understands the following aesthetics (required aesthetics are in bold): - **x** - **y** - alpha - colour - fill - group - shape - size - stroke ] .pull-right[ <img src="img/Screenshot 2023-03-20 223431.png"> ] --- .pull-left[ ### shape ```r wc3_units %>% ggplot(aes(race, hp, color = armor_type)) + * geom_point(aes(shape = air_attack), * size = 5, alpha = 0.5) ``` <!-- --> ] .pull-right[ <!-- --> ] --- .pull-left[ ### позиционирование параметров ```r wc3_units %>% ggplot(aes(race, hp, color = armor_type)) + * geom_point(aes(shape = air_attack, * size = armor, alpha = sight)) ``` - **shape**, **size** и **alpha** появились в легенде ] .pull-right[ <!-- --> ] --- # Типы геометрий Чтобы увидеть все доступные типы геометрий с описанием введите в консоли: ```r ??geom_ ``` Или начните вводить **geom_** и нажмите **Tab** --- <img src="img/geoms.png"> --- <br>Перед тем как начать подробно рассматривать геометрии <br>Для построения графиков нам нужно будет модифицировать данные <br>Мы рассмотрим два способа: - **stat_summary()** внутри ggplot - подготовка данных при помощи **dplyr** (group_by(), summarise(), pivot_longer()) <br> <br> <br>Примеры будут по ходу лекции --- .pull-left[ ### geom_point() ```r ggplot(data = wc3_units, aes(x = gold, y = hp)) + * geom_point() ``` <br> **geom_point()** - отрисовывает переменные, поданные в аэстетики (aes), в виде точек. Получилась обычная диаграмма рассеяния! <br>geom_point( <br> mapping = NULL, <br> data = NULL, <br> stat = "identity", <br> position = "identity", <br> ..., <br> na.rm = FALSE, <br> show.legend = NA, <br> inherit.aes = TRUE <br>) ] .pull-right[ <!-- --> ] --- .pull-left[ ### geom_point() ```r wc3_units %>% ggplot(aes(x = damage, y = gold))+ geom_point(size = 4) ``` Построим зависимость damage от gold ] .pull-right[ <!-- --> ] --- .pull-left[ ### geom_smooth() ```r wc3_units %>% ggplot(aes(x = damage, y = gold))+ geom_point(size = 4)+ * geom_smooth() ``` <br>Добавим регрессионную линию с помощью geom_smooth() <br>По умолчанию линия не прямая, пытается максимально приблизить точки. ] .pull-right[ ``` ## `geom_smooth()` using method = 'loess' and formula = 'y ~ x' ``` <!-- --> ] --- .pull-left[ ### geom_smooth() ```r wc3_units %>% ggplot(aes(x = damage, y = gold))+ geom_point(size = 4)+ * geom_smooth(method = 'lm') ``` <br>Добавим регрессионную прямую с помощью geom_smooth(method = 'lm') ] .pull-right[ ``` ## `geom_smooth()` using formula = 'y ~ x' ``` <!-- --> ] --- .pull-left[ ### geom_smooth() ```r wc3_units %>% ggplot(aes(x = damage, y = gold, * color = race))+ geom_point(size = 4)+ geom_smooth(method = 'lm') ``` <br>Добавим race юнитов с помощью цвета color в aes() <br>Обратите внимание, как прописываются aesthetics. В функции ggplot() применяются на всем графике, на всех geoms, поэтому geom_smooth() строит регрессию отдельно по каждой расе. <br>Если бы мы хотели построить регрессию по всему датасету, то аэстетику цвета нужно было бы прописать отдельно в geom_point() ] .pull-right[ ``` ## `geom_smooth()` using formula = 'y ~ x' ``` <!-- --> ] --- .pull-left[ ### geom_smooth() ```r wc3_units %>% ggplot(aes(x = damage, y = gold))+ * geom_point(aes(color = race), size = 4)+ geom_smooth(method = 'lm') ``` <br>Если бы мы хотели построить регрессию по всему датасету, то аэстетику цвета нужно было бы прописать отдельно в geom_point() ] .pull-right[ ``` ## `geom_smooth()` using formula = 'y ~ x' ``` <!-- --> ] --- .pull-left[ ### geom_histogram() ```r wc3_units %>% ggplot(aes(hp)) + * geom_histogram() ``` По умолчанию по оси у отложено количество наблюдений в диапазоне, определенном параметром bins или binwidth ] .pull-right[ <!-- --> ] --- .pull-left[ ### geom_histogram() ### bins ```r wc3_units %>% ggplot(aes(hp)) + * geom_histogram(bins = 5) ``` bins определяет количество долей на которые будут разделены данные ] .pull-right[ <!-- --> ] --- .pull-left[ ### geom_histogram() ### binwidth ```r wc3_units %>% ggplot(aes(hp)) + * geom_histogram(binwidth = 20) ``` binwidth определяет какого размера будут bins ] .pull-right[ <!-- --> ] --- .pull-left[ ### geom_histogram() ```r wc3_units %>% ggplot(aes(hp)) + geom_histogram(binwidth = 40, * colour = 4, fill = "white") ``` ] .pull-right[ <!-- --> ] --- .pull-left[ ### geom_boxplot() ```r wc3_units %>% ggplot(aes(race, hp)) + * geom_boxplot() ``` В описании к geom_boxplot() отмечено что подсчет статистик для него отличается от baser функции boxplot() <img src="img/bp.png"> ] .pull-right[ <!-- --> ] --- .pull-left[ ### geom_violin() ```r wc3_units %>% ggplot(aes(race, hp)) + * geom_violin() ``` <img src="img/v.png"> ] .pull-right[ <!-- --> ] --- .pull-left[ ### geom_violin() ```r wc3_units %>% ggplot(aes(race, hp)) + geom_violin()+ * geom_boxplot(width=0.1) ``` ] .pull-right[ <!-- --> ] --- .pull-left[ ### geom_violin() ```r wc3_units %>% ggplot(aes(race, hp)) + geom_violin()+ * geom_dotplot(binaxis='y', * stackdir='center', dotsize=1) ``` ] .pull-right[ <!-- --> ] --- .pull-left[ ### geom_bar() ```r wc3_units %>% ggplot(aes(hp)) + * geom_bar() ``` ] .pull-right[ <!-- --> по умолчанию параметр stat = "count" ] --- .pull-left[ ### geom_bar() Приведем таблицу к виду: ```r wc3_units %>% group_by(race) %>% summarise(mean_hp=mean(hp)) ``` ``` ## # A tibble: 4 × 2 ## race mean_hp ## <chr> <dbl> ## 1 Human 556. ## 2 N.Elf 649. ## 3 Orc 483. ## 4 Undead 518. ``` и построим график ```r wc3_units %>% group_by(race) %>% summarise(mean_hp=mean(hp)) %>% ggplot(aes(race, mean_hp)) + * geom_bar(stat = "identity") ``` ] .pull-right[ Чтобы посмотреть на средние значения по расе: <!-- --> ] --- .pull-left[ ### geom_bar() ```r wc3_units %>% group_by(race) %>% summarise(mean_hp=mean(hp)) %>% ggplot(aes(race, mean_hp, * fill=mean_hp)) + geom_bar(stat = "identity") + * scale_fill_gradient2(low="blue", high="red", * midpoint = 550) ``` <br>scale_fill_gradient позволяет выставить градиент ] .pull-right[ <!-- --> ] --- .pull-left[ ### geom_bar() ```r * library(viridis) wc3_units %>% group_by(race) %>% summarise(mean_hp=mean(hp)) %>% ggplot(aes(race, mean_hp, fill=mean_hp)) + geom_bar(stat = "identity") + * scale_fill_viridis() ``` <br>scale_fill_gradient позволяет выставить градиент ] .pull-right[ ``` ## Loading required package: viridisLite ``` <!-- --> ] --- .pull-left[ ### stat_summary() ```r wc3_units %>% ggplot(aes(race, hp)) + * stat_summary(geom = "bar", fun="mean") ``` <img src="img/sumf.png"> ] .pull-right[ <!-- --> то же самое можно задать при помощи **stat_summary()** ] --- .pull-left[ ### stat_summary() ```r wc3_units %>% ggplot(aes(race, hp)) + stat_summary(geom = "bar", fun="mean")+ * stat_summary(geom = "errorbar", * fun.data="mean_se", width = 0.2) ``` ] .pull-right[ <!-- --> дорисуем усы со стандартной ошибкой среднего ] --- .pull-left[ ### Надстройки ```r wc3_units %>% ggplot(aes(race, hp)) + stat_summary(geom = "bar", fun="mean")+ stat_summary(geom = "errorbar", fun.data="mean_se", width = 0.2)+ * geom_point() ``` <br> <br>на основе этого кода потренируемся создавать сложные графики <br>На одном плоте можно рисовать несколько геометрий ] .pull-right[ <!-- --> ] --- .pull-left[ ### position_jitterdodge() ```r wc3_units %>% ggplot(aes(race, hp)) + stat_summary(geom = "bar", fun="mean")+ stat_summary(geom = "errorbar", fun.data="mean_se", width = 0.2)+ geom_point(aes(color=armor_type), * position = position_jitterdodge(seed=1)) ``` <br>Фиксация генератора случайных чисел: <br>Для воспроизводимости положения точек мы указываем **seed** (для создания списка "рандомных" позиций) ] .pull-right[ <!-- --> ] --- .pull-left[ ### geom_text() ```r plt <- wc3_units %>% ggplot(aes(race, hp)) + stat_summary(geom = "bar", fun="mean")+ stat_summary(geom = "errorbar", fun.data="mean_se", width = 0.2)+ geom_point(aes(color=armor_type), position = position_jitterdodge(seed=1))+ * geom_text(aes(label = unit,color=armor_type), * position = position_jitterdodge(seed = 1), * size = 3) ``` Чтобы позиции текста и точек совпали на графике необходимо чтобы **seed** указанный для geom_point() соответствовал значению **seed** у geom_text() ] .pull-right[ <!-- --> ] --- .pull-left[ ### theme_() ```r plt + * ggtitle("Title") + * xlab("x") + * ylab("y") + * theme_dark() ``` сохраним в переменную plt ```r #??theme ``` [base r themes](https://ggplot2.tidyverse.org/reference/ggtheme.html) ] .pull-right[ <!-- --> ] --- .pull-left[ ### theme() ```r plt + ggtitle("Title") + xlab("x") + ylab("y") + * theme(panel.border = element_rect(linetype = "dashed", fill = NA)) ``` ] .pull-right[ <!-- --> ] --- .pull-left[ ### theme() ```r plt + ggtitle("Title") + xlab("x") + ylab("y") + * theme(axis.text = element_text(colour = "blue")) ``` ] .pull-right[ <!-- --> ] --- .pull-left[ ### theme() ```r plt + ggtitle("Title") + xlab("x") + ylab("y") + * theme(axis.text.x = element_text(angle = 90, * vjust = 0.5, hjust=1)) ``` ] .pull-right[ <!-- --> ] --- .pull-left[ ### scales ```r plt + scale_y_continuous(limits = c(0,600)) ``` ] .pull-right[ <!-- --> ] --- .pull-left[ ### scales ```r plt + * scale_y_continuous(limits = c(0,1500), * breaks = seq(0, 1500, 300)) ``` ] .pull-right[ <!-- --> ] --- .pull-left[ ### facet_wrap() ```r plt + ggtitle("Title") + xlab("x") + ylab("y") + theme_bw() + * facet_wrap(~armor_type) ``` ] .pull-right[ <!-- --> ] --- .pull-left[ ### facet_wrap() ```r plt + ggtitle("Title") + xlab("x") + ylab("y") + theme_bw() + facet_wrap(~armor_type, * scales = "free") ``` ] .pull-right[ <!-- --> ] --- .pull-left[ ### factor levels ```r wc3_units %>% * mutate(armor_type = * factor(armor_type, * levels=c("Unarmored", "Light", "Medium", * "Heavy", "Fort", "Invulnerable"))) %>% ggplot(aes(race, hp)) + stat_summary(geom = "bar", fun="mean")+ stat_summary(geom = "errorbar", fun.data="mean_se", width = 0.2)+ geom_point(aes(color=armor_type), position = position_jitterdodge(seed=1))+ ggtitle("Title") + xlab("x")+ ylab("y")+ theme_bw() + facet_wrap(~armor_type) ``` ] .pull-right[ <!-- --> ] --- # ggplotly() <br>пакет для создания интерактивных графиков <br>[plotly](https://plotly.com/r/getting-started/): ```r install.packages("plotly") ``` <br>**echarts4r** — один из основных конкурентов для plotly. Симпатичный, работает довольно плавно, синтаксис тоже пытается вписаться в логику tidyverse. <br>**leaflet** — основной (но не единственный!) пакет для работы с картами. Leaflet — это очень популярная библиотека JavaScript, используемая во многих веб-приложениях, а пакет leaflet - это довольно понятный интерфейс к ней с широкими возможностями. <br>**networkD3** — пакет для интерактивной визуализации сетей. Подходит для небольших сетей. --- .pull-left[ ### ggplotly() ```r ggplotly(plt) ``` ] .pull-right[
] --- .pull-left[ ### ggplotly() ```r library(viridis) plt2 <- wc3_units %>% ggplot(aes(text=unit,damage, hp)) + geom_point(aes(size=damage,color=dps)) + scale_color_viridis() ggplotly(plt2) ``` ] .pull-right[
] --- ### Диаграмма Венна [Диаграммы Венна в R](https://r-graph-gallery.com/14-venn-diagramm) <br><img src="img/b.png"> --- ### UpSetR <br>[UpSetR tutorial](https://jokergoo.github.io/ComplexHeatmap-reference/book/upset-plot.html) <br>[Туториал от Лены](https://t.me/stats_for_science/61) <br><img src="img/upset.png"> --- .left-code[ ### ComplexHeatmap [ComplexHeatmap](https://jokergoo.github.io/ComplexHeatmap-reference/book/): ```r if (!require("BiocManager", quietly = TRUE)) install.packages("BiocManager") BiocManager::install("ComplexHeatmap") ``` [Примеры](https://github.com/jokergoo/ComplexHeatmap) ] .right-plot[ <img src="img/ch.png"> ] --- ### ComplexHeatmap на вход подается матрица ```r mat[1:8,1:8] ``` <table> <thead> <tr> <th style="text-align:left;"> </th> <th style="text-align:left;"> col1 </th> <th style="text-align:left;"> col2 </th> <th style="text-align:left;"> col3 </th> <th style="text-align:left;"> col4 </th> <th style="text-align:left;"> col5 </th> <th style="text-align:left;"> col6 </th> <th style="text-align:left;"> col7 </th> <th style="text-align:left;"> col8 </th> </tr> </thead> <tbody> <tr> <td style="text-align:left;"> row1 </td> <td style="text-align:left;"> 0.9 </td> <td style="text-align:left;"> -0.4 </td> <td style="text-align:left;"> 0.5 </td> <td style="text-align:left;"> 1.3 </td> <td style="text-align:left;"> 0.8 </td> <td style="text-align:left;"> 0.2 </td> <td style="text-align:left;"> -0.3 </td> <td style="text-align:left;"> 0.7 </td> </tr> <tr> <td style="text-align:left;"> row2 </td> <td style="text-align:left;"> 0.9 </td> <td style="text-align:left;"> 0.8 </td> <td style="text-align:left;"> 1.1 </td> <td style="text-align:left;"> 0.0 </td> <td style="text-align:left;"> 0.1 </td> <td style="text-align:left;"> 0.5 </td> <td style="text-align:left;"> 1.3 </td> <td style="text-align:left;"> 0.4 </td> </tr> <tr> <td style="text-align:left;"> row3 </td> <td style="text-align:left;"> 0.3 </td> <td style="text-align:left;"> 0.0 </td> <td style="text-align:left;"> 0.7 </td> <td style="text-align:left;"> 1.2 </td> <td style="text-align:left;"> 0.2 </td> <td style="text-align:left;"> 0.2 </td> <td style="text-align:left;"> -0.6 </td> <td style="text-align:left;"> -0.3 </td> </tr> <tr> <td style="text-align:left;"> row4 </td> <td style="text-align:left;"> 0.0 </td> <td style="text-align:left;"> 0.8 </td> <td style="text-align:left;"> 0.5 </td> <td style="text-align:left;"> -0.5 </td> <td style="text-align:left;"> -0.5 </td> <td style="text-align:left;"> 0.6 </td> <td style="text-align:left;"> 0.8 </td> <td style="text-align:left;"> 0.0 </td> </tr> <tr> <td style="text-align:left;"> row5 </td> <td style="text-align:left;"> -0.3 </td> <td style="text-align:left;"> 1.0 </td> <td style="text-align:left;"> 1.1 </td> <td style="text-align:left;"> 0.7 </td> <td style="text-align:left;"> 0.4 </td> <td style="text-align:left;"> 1.0 </td> <td style="text-align:left;"> 2.6 </td> <td style="text-align:left;"> 0.8 </td> </tr> <tr> <td style="text-align:left;"> row6 </td> <td style="text-align:left;"> 0.6 </td> <td style="text-align:left;"> -0.5 </td> <td style="text-align:left;"> 0.5 </td> <td style="text-align:left;"> 0.9 </td> <td style="text-align:left;"> -0.2 </td> <td style="text-align:left;"> 0.0 </td> <td style="text-align:left;"> -0.3 </td> <td style="text-align:left;"> 1.1 </td> </tr> <tr> <td style="text-align:left;"> row7 </td> <td style="text-align:left;"> 0.4 </td> <td style="text-align:left;"> 1.1 </td> <td style="text-align:left;"> 0.2 </td> <td style="text-align:left;"> 0.4 </td> <td style="text-align:left;"> 1.3 </td> <td style="text-align:left;"> 1.6 </td> <td style="text-align:left;"> 0.8 </td> <td style="text-align:left;"> 0.0 </td> </tr> <tr> <td style="text-align:left;"> row8 </td> <td style="text-align:left;"> 2.2 </td> <td style="text-align:left;"> 0.6 </td> <td style="text-align:left;"> 0.8 </td> <td style="text-align:left;"> 0.8 </td> <td style="text-align:left;"> 0.7 </td> <td style="text-align:left;"> -0.3 </td> <td style="text-align:left;"> -0.2 </td> <td style="text-align:left;"> 0.5 </td> </tr> </tbody> </table> --- ### ComplexHeatmap .pull-left[ ```r Heatmap(mat) ``` ] .pull-right[ <!-- --> ] --- # Куда двигаться дальше <br>[Понятная презентация по ggplot2](https://pkg.garrickadenbuie.com/gentle-ggplot2/) <br>[gganimate](https://gganimate.com/) - анимированные ggplots <br>[ggforce](https://ggforce.data-imaginist.com/) - еще более красивые графики <br>[Data Imaginist](https://www.data-imaginist.com/) - блог по визуализации данных --- class: inverse .center[ ## Спасибо за внимание! <img src="img/cat.jpg"> ] .right[ Если вам понравилось сканируйте QR-код ;) <img src="img/qr.png"> ]