Базовая графика

Типы данных

Точковая диаграмма

head(mtcars, 2)
              mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4      21   6  160 110  3.9 2.620 16.46  0  1    4    4
Mazda RX4 Wag  21   6  160 110  3.9 2.875 17.02  0  1    4    4
plot(mtcars$mpg, mtcars$hp)

Точковая диаграмма - подписи

plot(mtcars$mpg, mtcars$hp,
     main = 'Точечки',
     xlab = 'Miles/(US) gallon', ylab = 'Gross horsepower')

Точковая диаграмма - цвета, размер

Цвета задаются по умолчанию

plot(mtcars$mpg, mtcars$hp, cex = 2, pch = 16, col = mtcars$cyl,
     cex.lab = 1.5, cex.axis = 2)

Точковая диаграмма - цвета

Можно задать цвета вручную

# Именованный вектор цветов

species_colors <- c(
  "setosa" = "red",
  "versicolor" = "green",
  "virginica" = "blue"
)

species_colors
    setosa versicolor  virginica 
     "red"    "green"     "blue" 

Точковая диаграмма - цвета

Можно задать цвета вручную

# Назначаем точкам цвета

point_colors <- species_colors[iris$Species]

point_colors
    setosa     setosa     setosa     setosa     setosa     setosa     setosa 
     "red"      "red"      "red"      "red"      "red"      "red"      "red" 
    setosa     setosa     setosa     setosa     setosa     setosa     setosa 
     "red"      "red"      "red"      "red"      "red"      "red"      "red" 
    setosa     setosa     setosa     setosa     setosa     setosa     setosa 
     "red"      "red"      "red"      "red"      "red"      "red"      "red" 
    setosa     setosa     setosa     setosa     setosa     setosa     setosa 
     "red"      "red"      "red"      "red"      "red"      "red"      "red" 
    setosa     setosa     setosa     setosa     setosa     setosa     setosa 
     "red"      "red"      "red"      "red"      "red"      "red"      "red" 
    setosa     setosa     setosa     setosa     setosa     setosa     setosa 
     "red"      "red"      "red"      "red"      "red"      "red"      "red" 
    setosa     setosa     setosa     setosa     setosa     setosa     setosa 
     "red"      "red"      "red"      "red"      "red"      "red"      "red" 
    setosa versicolor versicolor versicolor versicolor versicolor versicolor 
     "red"    "green"    "green"    "green"    "green"    "green"    "green" 
versicolor versicolor versicolor versicolor versicolor versicolor versicolor 
   "green"    "green"    "green"    "green"    "green"    "green"    "green" 
versicolor versicolor versicolor versicolor versicolor versicolor versicolor 
   "green"    "green"    "green"    "green"    "green"    "green"    "green" 
versicolor versicolor versicolor versicolor versicolor versicolor versicolor 
   "green"    "green"    "green"    "green"    "green"    "green"    "green" 
versicolor versicolor versicolor versicolor versicolor versicolor versicolor 
   "green"    "green"    "green"    "green"    "green"    "green"    "green" 
versicolor versicolor versicolor versicolor versicolor versicolor versicolor 
   "green"    "green"    "green"    "green"    "green"    "green"    "green" 
versicolor versicolor versicolor versicolor versicolor versicolor versicolor 
   "green"    "green"    "green"    "green"    "green"    "green"    "green" 
versicolor versicolor  virginica  virginica  virginica  virginica  virginica 
   "green"    "green"     "blue"     "blue"     "blue"     "blue"     "blue" 
 virginica  virginica  virginica  virginica  virginica  virginica  virginica 
    "blue"     "blue"     "blue"     "blue"     "blue"     "blue"     "blue" 
 virginica  virginica  virginica  virginica  virginica  virginica  virginica 
    "blue"     "blue"     "blue"     "blue"     "blue"     "blue"     "blue" 
 virginica  virginica  virginica  virginica  virginica  virginica  virginica 
    "blue"     "blue"     "blue"     "blue"     "blue"     "blue"     "blue" 
 virginica  virginica  virginica  virginica  virginica  virginica  virginica 
    "blue"     "blue"     "blue"     "blue"     "blue"     "blue"     "blue" 
 virginica  virginica  virginica  virginica  virginica  virginica  virginica 
    "blue"     "blue"     "blue"     "blue"     "blue"     "blue"     "blue" 
 virginica  virginica  virginica  virginica  virginica  virginica  virginica 
    "blue"     "blue"     "blue"     "blue"     "blue"     "blue"     "blue" 
 virginica  virginica  virginica 
    "blue"     "blue"     "blue" 

Точковая диаграмма - цвета

Можно задать цвета вручную

plot(iris$Petal.Length, iris$Petal.Width, col = point_colors,
     pch = 16, main = "Ирисы с ручной раскраской",
     xlab = "Длина лепестка", ylab = "Ширина лепестка")

legend("topleft", legend = names(species_colors),
       col = species_colors, pch = 16)

Бобры

x <- beaver1[beaver1$day == 346,]
plot(x$time, x$temp)

Линии

plot(x$time, x$temp, type = 'l')

И точки и линии

plot(x$time, x$temp, type = 'o')

Ирисы

head(iris)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

Попарные точковые диаграммы

pairs(iris)

Попарные точковые диаграммы - цвета

pairs(iris, col = iris$Species)

Столбчатая диаграмма

table(mtcars$cyl)

 4  6  8 
11  7 14 
barplot(table(mtcars$cyl))

Столбчатая диаграмма

Чуть посложнее и покрасивее

table(mtcars$cyl)

 4  6  8 
11  7 14 
barplot(table(mtcars$cyl),
        col = "#3a86d4", border = "black",
        main = "Cars by cylinder count",
        xlab = "Cylinders", ylab = "Number of cars")

Столбчатая диаграмма с группами

Возможно внутри одной группы есть другие группы

В данных mtcars для каждой машины известно количество цилиндров (cyl) и тип трансмиссии (am)

Давайте попробуем узнать, как представлен каждый тип трансмиссии в каждой группе автомобилей с одинаковым количеством цилиндров

Для начала сделаем таблицу

amcyl <- table(mtcars$am, mtcars$cyl)
amcyl
   
     4  6  8
  0  3  4 12
  1  8  3  2

Столбчатая диаграмма с группами

Теперь визуализируем результат

barplot(amcyl)

Столбчатая диаграмма с группами

Теперь визуализируем результат

bar_colors <- c('orange', 'violet')
barplot(amcyl, col = bar_colors, 
        border = "black",
        legend = rownames(amcyl))

Столбчатая диаграмма с группами

Поправим легенду

bar_colors <- c('orange', 'violet')
barplot(amcyl, col = bar_colors, 
        border = "black")
legend("top", legend = rownames(amcyl),
       fill = bar_colors, box.lty = 0, cex = 0.8)

Столбчатая диаграмма с группами

Расположим подгруппы иначе

bar_colors <- c('orange', 'violet')
barplot(amcyl, col = bar_colors, 
        border = "black", beside = TRUE)
legend("top", legend = rownames(amcyl),
       fill = bar_colors, box.lty = 0, cex = 0.8)

Столбчатая диаграмма с группами

Расположим подгруппы еще более иначе

bar_colors <- c('orange', 'violet')
barplot(amcyl, col = bar_colors, 
        border = "black", beside = TRUE,
        horiz = TRUE, las = 1,)
legend("bottomright", legend = rownames(amcyl),
       fill = bar_colors, box.lty = 0, cex = 0.8)

Гистограмма

hist(mtcars$mpg)

Гистограмма - breaks

hist(mtcars$mpg, breaks = 10)

Гистограмма - breaks

hist(mtcars$mpg, breaks = c(10, 20, 25, 30, 35))

Несколько гистограмм

Нарисуем сначала одну, зачем добавим к ней другую

hist(iris[iris$Species == 'setosa',]$Sepal.Length, xlim = c(3, 10), breaks = seq(3, 10, 0.2), col = 'lightblue')
hist(iris[iris$Species == 'virginica',]$Sepal.Length, xlim = c(3, 10), add=T, breaks = seq(3, 10, 0.2), col=rgb(1,0,0,0.5),
     main = 'Distribution of sepal lengths in two iris species', xlab = "Sepal length, mm")

Несколько гистограмм

Добавим вертикальные линии с средними значениями

hist(iris[iris$Species == 'setosa',]$Sepal.Length, xlim = c(3, 10), breaks = seq(3, 10, 0.2), col = 'lightblue')
hist(iris[iris$Species == 'virginica',]$Sepal.Length, xlim = c(3, 10), add=T, breaks = seq(3, 10, 0.2), col=rgb(1,0,0,0.5),
     main = 'Distribution of sepal lengths in two iris species', xlab = "Sepal length, mm")
abline(v=mean(iris[iris$Species == 'setosa',]$Sepal.Length), col='blue', lwd=3, lty='dashed')
abline(v=mean(iris[iris$Species == 'virginica',]$Sepal.Length), col='red', lwd=3, lty='dashed')

Диаграмма размахов

Диаграмма размахов

boxplot(iris$Sepal.Length ~ iris$Species)

Зачем

помнить про типы данных?

Чтение и запись

Сохранение данных

write.table(swiss,file='swiss.tab',quote=T,col.names = T,row.names=T,sep='\t')
write.csv(swiss,file='swiss.csv')
save(swiss,file='swiss.RData')

Чтение данных

mt <- read.table('swiss.tab',sep='\t',header=T)
head(mt)
             Fertility Agriculture Examination Education Catholic
Courtelary        80.2        17.0          15        12     9.96
Delemont          83.1        45.1           6         9    84.84
Franches-Mnt      92.5        39.7           5         5    93.40
Moutier           85.8        36.5          12         7    33.77
Neuveville        76.9        43.5          17        15     5.16
Porrentruy        76.1        35.3           9         7    90.57
             Infant.Mortality
Courtelary               22.2
Delemont                 22.2
Franches-Mnt             20.2
Moutier                  20.3
Neuveville               20.6
Porrentruy               26.6

Чтение данных

mt <- read.table('swiss.tab',skip=2)
head(mt)
            V1   V2   V3 V4 V5    V6   V7
1     Delemont 83.1 45.1  6  9 84.84 22.2
2 Franches-Mnt 92.5 39.7  5  5 93.40 20.2
3      Moutier 85.8 36.5 12  7 33.77 20.3
4   Neuveville 76.9 43.5 17 15  5.16 20.6
5   Porrentruy 76.1 35.3  9  7 90.57 26.6
6        Broye 83.8 70.2 16  7 92.85 23.6

Чтение данных

mt <- read.table('swiss.tab', skip=2, header=T)
head(mt)
      Delemont X83.1 X45.1 X6 X9 X84.84 X22.2
1 Franches-Mnt  92.5  39.7  5  5  93.40  20.2
2      Moutier  85.8  36.5 12  7  33.77  20.3
3   Neuveville  76.9  43.5 17 15   5.16  20.6
4   Porrentruy  76.1  35.3  9  7  90.57  26.6
5        Broye  83.8  70.2 16  7  92.85  23.6
6        Glane  92.4  67.8 14  8  97.16  24.9

RData

rm(list=ls())
ls()
character(0)
load('swiss.RData')
ls()
[1] "swiss"

Генерация случайных данных

Взять 10 случайных чисел 🏠

от 1 до 30

sample(1:30, 10, replace = T)
 [1]  8  4 30 18 22  2 18 20  6 27
sample(1:30, 10, replace = T)
 [1] 24  9 24 28 14 22  5 24  6  9
set.seed(123)
sample(1:30, 10, replace = T)
 [1] 15 19 14  3 10 18 22 11  5 20
set.seed(123)
sample(1:30, 10, replace = T)
 [1] 15 19 14  3 10 18 22 11  5 20

set.seed(), sample() 🏠

Получить числа из известного распределения 🏠

  • rnorm(n, mean, sd) - нормальное распределение
  • runif(n, min, max) - равномерное распределение
  • rbinom(n, size, prob) - биномиальное распределение
  • rpois(n, lambda) - распределение Пуассона
set.seed(123)
rpois(20,10)
 [1]  8  9 14 10 10 15 11  5  4 13 11 11 10  8 15 11  3  7  6  8

Немного о функциях

Разберем функцию rnorm

В вкладке “Help” можно вызвать справочную информацию о функции

rnorm(n, mean = 0, sd = 1)

У функции есть параметры с значениями по умолчанию

set.seed(123)
rnorm(3) # получим 3 случайных значения из стандартного нормального распределения
[1] -0.5604756 -0.2301775  1.5587083

Немного о функциях

set.seed(123)
rnorm(3, mean = 1, sd = 2) # указываем значения параметров
[1] -0.1209513  0.5396450  4.1174166
set.seed(123)
rnorm(3, 1, 2) # чаще всего можно не указывать имена параметров в явном виде 
[1] -0.1209513  0.5396450  4.1174166

Конец!