library(datasets)
str(iris)
## 'data.frame': 150 obs. of 5 variables:
## $ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
## $ Sepal.Width : num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
## $ Petal.Length: num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
## $ Petal.Width : num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
## $ Species : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
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
Biểu đồ cho biến định tính
Biểu đồ thanh (barplot) và biểu đồ tròn (pie chart)
table(iris$Species)
##
## setosa versicolor virginica
## 50 50 50
par(mfrow=c(1,2))
barplot(table(iris$Species))
pie(table(iris$Species))

Biểu đồ thanh
barplot(table(iris$Species), col = c("red", "blue", "yellow"))
title(main = "Bieu do thanh cho ba loai hoa Iris")

Biểu đồ tròn
pie(table(iris$Species), col = rainbow(3))
title(main = "Bieu do tron cho ba loai hoa Iris")

ti_le <- round(prop.table(table(iris$Species)),3)*100 # Tinh ti le
ti_le
##
## setosa versicolor virginica
## 33.3 33.3 33.3
pie(table(iris$Species),
col = rainbow(3),
labels = paste(iris$Species, ":" , ti_le,"%") # them phan tram
)
title(main = "Bieu do tron cho ba loai hoa Iris")

Biểu đồ cho biến định lượng
Biểu đồ phân phối tần số (Histogram)
names(iris)
## [1] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width" "Species"
hist(iris$Sepal.Length)

hist(iris$Sepal.Length[iris$Species == 'setosa'])

hist(iris$Sepal.Length[iris$Species == 'versicolor'])

hist(iris$Sepal.Length[iris$Species == 'virginica'])

vir_sepal <- iris$Sepal.Length[iris$Species == 'virginica']
hist(vir_sepal, col = "lightblue",
labels = TRUE, # Dien tan so tren moi cot
main = "Bieu do phan phoi tan so")

Biểu đồ hộp
boxplot(iris$Sepal.Length)

boxplot(iris$Sepal.Length ~ iris$Species, col = "orange")
title("Bieu do hop cho ba loai hoa Iris")

Biểu đồ tán xạ
plot(iris$Sepal.Length)

plot(iris$Sepal.Length, iris$Sepal.Width)

plot(iris$Sepal.Length[iris$Species=='setosa'], iris$Sepal.Width[iris$Species=='setosa'])
