ASPRAK VISDAT

Minggu 1 dan 2

Fungsi R Base

Contoh data yang digunakan adalah dataset IRIS, dataset tersebut menyediakan informasi tentang tiga spesies bunga iris (Setosa, Versicolor dan Virginica) dengan 4 fitur/kolom yaitu panjang dan lebar kelopak bunga serta panjang dan lebar mahkota.

# Data
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
data <- iris
head(data)
##   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
#View(data)

Fungsi Dasar Plot di R

  1. plot : fungsi dasar untukmembuat scatterplot, line plot dan plot lainnya
  2. line : untuk menambahkan garis pada plot yang telah dibuat
  3. par : mengatur tampilan dan posisi plot/grafik
  4. hist : membuat histogram
  5. boxplot : membuat boxplot
  6. text : menambahkan teks pada plot yang telah dibuat
  7. legend : menambahkan legend
  8. mosaic plot : membuat mosaik plot
  9. barplot : membuat barplot 10.main : judul 11.xlab : label pada sumbu x 12.ylab : label pada sumbu y 13.col : warna 14.cex : mengatur ukuran titik data 15.pch : mengatur tipe titik data 16.lwd : mengatur ketebalan garis 17.lty : tipe garis 18.table : menghitung frekuensi data kategorik 19.font : jenis font

Fungsi plot() untuk membuat line plot

fungsi dasarnya yaitu plot(x, y, type=" "). Variabel x dan y merupakan data dengan panjang dan jumlah yang sama. type adalah jenis grafik scatter plot yang ingin dibuat. Nilai yang dapat dimasukkan antara lain:

  1. p = plot titik atau scatter plot biasa
  2. l = plot garis
  3. b = plot titik yang dihubungkan garis
  4. o = plot titik yang dilapisi garis
  5. h = plot garis vertikal
  6. s = plot tangga
  7. n = tanpa grafik
# Contoh
# membagi tampilan grafik menjadi 2 baris dan 4 kolom
par(mfrow=c(2,4))

# grafik
x <- c(1:10); y <- (x^2)+2
type <- c("p","l","b","o","h","s","n")
for (i in type){
  plot(x, y, type=i, main = paste("type =", i))
}
# mengatur bentuk titik
plot(x,y,type = "p", pch=2)

Bar Plot

Bar plot digunakan untuk visualisasi data mengenai jumlah atau frekuensi.

par(mfcol=c(1,2))
barplot(table(data$Species), col = c("darkorange", "skyblue", "pink"), border = "darkred",
        main = "Data Spesies Bunga", xlab = "jenis", ylab = "jumlah", col.lab = "black", col.main = "darkblue",
        cex.lab = 0.8, space=0.5, font.main=9)

barplot(table(data$Species), col = c("darkorange", "skyblue", "pink"), border = "darkred",
        main = "Data Spesies Bunga", xlab = "jenis", ylab = "jumlah", col.lab = "black", col.main = "darkblue",
        cex.lab = 0.8, horiz = TRUE)

Data Mobil

library(readxl)
data.mobil <- read_xlsx("D:/ASPRAK VISDAT/CarPrice_Assignment.xlsx")
head(data.mobil)
## # A tibble: 6 × 26
##   car_ID symboling CarName     fueltype aspiration doornumber carbody drivewheel
##    <dbl>     <dbl> <chr>       <chr>    <chr>      <chr>      <chr>   <chr>     
## 1      1         3 alfa-romer… gas      std        two        conver… rwd       
## 2      2         3 alfa-romer… gas      std        two        conver… rwd       
## 3      3         1 alfa-romer… gas      std        two        hatchb… rwd       
## 4      4         2 audi 100 ls gas      std        four       sedan   fwd       
## 5      5         2 audi 100ls  gas      std        four       sedan   4wd       
## 6      6         2 audi fox    gas      std        two        sedan   fwd       
## # ℹ 18 more variables: enginelocation <chr>, wheelbase <dbl>, carlength <dbl>,
## #   carwidth <dbl>, carheight <dbl>, curbweight <dbl>, enginetype <chr>,
## #   cylindernumber <chr>, enginesize <dbl>, fuelsystem <chr>, boreratio <dbl>,
## #   stroke <dbl>, compressionratio <dbl>, horsepower <dbl>, peakrpm <dbl>,
## #   citympg <dbl>, highwaympg <dbl>, price <dbl>
#install.packages("RColorBrewer")
library(RColorBrewer)
## Warning: package 'RColorBrewer' was built under R version 4.3.1
body.mobil <- table(data.mobil$carbody)
a <- data.frame(body.mobil)
a <- a[order(a$Freq, decreasing=TRUE),]

my_colors <- brewer.pal(n = length(data.mobil$carbody), name = "Pastel1")
## Warning in brewer.pal(n = length(data.mobil$carbody), name = "Pastel1"): n too large, allowed maximum for palette Pastel1 is 9
## Returning the palette you asked for with that many colors
barplot(a$Freq, names.arg=a$Var1, col = my_colors,
        main = "Data Tipe Body Mobil", xlab = "Tipe", ylab = "jumlah", col.lab = "black", col.main = "darkblue",
        cex.lab = 0.8, space=0.2, ylim=c(0, 100))

# Membuat data tabulasi silang
data.silang <- table(data.mobil$carbody, data.mobil$doornumber)
df <- as.matrix(data.silang)
# Membuat diagram batang dengan grup
barplot(df, col=c("red","skyblue","darkcyan","pink","darkorange"), legend=rownames(df), beside=TRUE,
         args.legend = list(x = "topright", cex = 0.8))

Histogram

Fungsi hist() dapat digunakan untuk membuat histogram pada R, secara sederhana fungsi tersebut dapat didefinisikan sebagai berikut : hist(x, break="sturges")

par(mfrow=c(2,2))

# histogram
hist(data.mobil$price, breaks=6, col = "orange", border = "darkred",
     main = "Histogram Harga Mobil", xlab="Harga")

# density plot
dens <- density(data.mobil$price, bw=1800) # menghitung density
plot(dens, col = "darkorange", type = "l", lwd = 2, main = "Density Plot", xlab = "Harga")

# histogram + density plot
dens <- density(data.mobil$price)
hist(data.mobil$price, breaks=6, col = "orange", border = "darkred",
     main = "Histogram Harga Mobil", xlab="Harga", freq = FALSE)
lines(dens, col = "black", lwd=2)

Boxplot

Boxplot dapat digunakan juga untuk melihat sebaran data dan mendeteksi adanya pencilan. Fungsi untuk membuat boxplot pada R sebagai berikut : boxplot()

par(mfrow=c(1,2))
# basic
boxplot(data.mobil$price)

# dikelompokkan factor
boxplot(data.mobil$price ~ data.mobil$carbody, at=c(1,2,3,4,5), cex.axis=0.5)

# dikelompokkan factor
boxplot(data.mobil$price ~ data.mobil$carbody, main = "Sebaran Data Harga Berdasarkan Type Body Mobil",
        xlab="Type Body Mobil", ylab="Harga", cex.axis=0.8, col = my_colors)

# dikelompokkan factor
data.mobil$carbody <- reorder(data.mobil$carbody, data.mobil$price, FUN = median)

boxplot(price ~ carbody, data = data.mobil, main = "Sebaran Data Harga Berdasarkan Type Body Mobil",
        xlab="Type Body Mobil", ylab="Harga", cex.axis=0.8, col = my_colors)

Berbagai Custom Lainnya

Untuk menambahkan judul pada plot secara langsung kita dapat menggunakan argumen tambahan sebagai berikut:

  1. main = teks untuk judul
  2. xlab = teks untuk keterangan sumbu x
  3. ylab = teks untuk keterangan sumbu y
  4. sub = teks untuk sub-judul

Untuk menambahkan warna, font style dan ukuran font judul dapat menggunakan argumen:

  1. col.main = warna untuk judul
  2. col.lab = warna untuk keterangan axis
  3. col.sub = warna untuk sub-judul

Untuk font judul, kita dapat menambahkan argumen berikut:

  1. font.main = gaya font untuk judul
  2. font.lab = gaya font untuk keterangan axis
  3. font.sub = gaya font untuk sub-judul
barplot(c(2,5), 
# menambahkan judul
main="Main title",
xlab="X axis title",
ylab="Y axis title",
sub="Sub-title",
# kustomisasi warna font
col.main="#990033", 
col.lab="blue", 
col.sub="#ff6666",
# kustomisasi font style
font.main=10, 
font.lab=4, 
font.sub=4,
# kustomisasi ukuran font
cex.main=2, 
cex.lab=1.7, 
cex.sub=1.2)

Fungsi legend() pada R dapat digunakan untuk menambahkan legend pada grafik. Format sederhananya adalah sebagai berikut: legend(x, y,legend, fill, col, bg).

  1. x dan y = koordinat posisi legend
  2. legend = teks pada legend
  3. fill = warna untuk mengisi box di samping legend
  4. col = warna garis dan titik di samping legend
  5. bg = warna latar belakang legend box
# membuat vektor numerik
x <- c(1:10)
y <- x^2
z <- x*2
# membuat line plot
plot(x,y, type="o", col="red", lty=1)
# menambahkan line plot
lines(x,z, type="o", col="blue", lty=2)
# menambahkan legend
legend(1, 98, legend=c("Line 1", "Line 2"),
col=c("red", "blue"), lty=1:2, cex=1)

Fungsi abline() dapat digunakan untuk menamabahkan garis pada plot. Garis yang ditambahkan dapat berupa garis vertikal, horizontal, maupun garis regresi

# membuat plot 
plot(mtcars$wt, mtcars$mpg, main="Milage vs. Car Weight", xlab="Weight", ylab="Miles/(US) gallon")

# menambahkan garis vertikal di titik rata-rata weight
abline(v=mean(mtcars$wt), col="red", lwd=3, lty=2)

# menambahkan garis horizontal di titik rata-rata mpg
abline(h=mean(mtcars$mpg), col="blue", lwd=3, lty=3)

# menambahkan garis regresi 
abline(lm(mpg~wt, data=mtcars), lwd=4, lty=4)

Fungsi ggplot

Pada pertemuan kedua ini, akan diilustrasikan visualisasi data menggunakan ggplot2. Sebagai ilustrasi, akan digunakan data mtcars yang tersedia pada package dplyr. Paket yang perlu diinstal: install.packages(“dplyr”) dan install.packages(“ggplot2”).

Data

library(readxl)
data.mobil <- read_xlsx("D:/ASPRAK VISDAT/CarPrice_Assignment.xlsx")
head(data.mobil)
## # A tibble: 6 × 26
##   car_ID symboling CarName     fueltype aspiration doornumber carbody drivewheel
##    <dbl>     <dbl> <chr>       <chr>    <chr>      <chr>      <chr>   <chr>     
## 1      1         3 alfa-romer… gas      std        two        conver… rwd       
## 2      2         3 alfa-romer… gas      std        two        conver… rwd       
## 3      3         1 alfa-romer… gas      std        two        hatchb… rwd       
## 4      4         2 audi 100 ls gas      std        four       sedan   fwd       
## 5      5         2 audi 100ls  gas      std        four       sedan   4wd       
## 6      6         2 audi fox    gas      std        two        sedan   fwd       
## # ℹ 18 more variables: enginelocation <chr>, wheelbase <dbl>, carlength <dbl>,
## #   carwidth <dbl>, carheight <dbl>, curbweight <dbl>, enginetype <chr>,
## #   cylindernumber <chr>, enginesize <dbl>, fuelsystem <chr>, boreratio <dbl>,
## #   stroke <dbl>, compressionratio <dbl>, horsepower <dbl>, peakrpm <dbl>,
## #   citympg <dbl>, highwaympg <dbl>, price <dbl>

Bar Plot

# Basic
library(ggplot2)
ggplot(data = data.mobil) +
       geom_bar(mapping=aes(x=data.mobil$drivewheel))
## Warning: Use of `data.mobil$drivewheel` is discouraged.
## ℹ Use `drivewheel` instead.

Pada umumnya, barplot ditampilkan secara terurut dari frekuensi yang paling besar. Sehingga kita dapat mengurutkan kelas berdasarkan frekuensi dnegan menggunakan Sebagai tambahan, kita dapat pula memberikan warna pada plot dengan menambahkan argumen fill, serta warna border setiap bar dengan argumen color, seperti contoh berikut ini.

library(dplyr)
data.mobil %>%
  count(drivewheel) %>%
  mutate(drivewheel = reorder(drivewheel, n, .asc=TRUE)) %>%
  ggplot(aes(x = drivewheel, y = n, fill=drivewheel)) + geom_bar(stat = 'identity')

ggplot(data.mobil, aes(x=data.mobil$cylindernumber, fill=data.mobil$aspiration))+
  geom_bar(position = "dodge")+
  labs(
    x="Jumlah Silinder Mesin",
    y="Jumlah",
    title="Sistem Mesin Berdasarkan Jumlah Silinder",
    subtitle = "ini subtitle"
  )+
  scale_fill_manual(values = c("orange", "darkred"))+
  theme_bw()+
  theme(plot.title = element_text(hjust = 0.5), plot.subtitle = element_text(hjust = 0.5))
## Warning: Use of `data.mobil$cylindernumber` is discouraged.
## ℹ Use `cylindernumber` instead.
## Warning: Use of `data.mobil$aspiration` is discouraged.
## ℹ Use `aspiration` instead.

a<-data.mobil %>%
  count(fuelsystem) %>%
  mutate(fuelsystem = reorder(fuelsystem, n, .desc = TRUE)) %>%
  ggplot(aes(x = fuelsystem, y = n, fill=fuelsystem))+ 
  geom_bar(stat = "identity", width = 0.8)+
  labs(
    x="sistem bahan bakar", 
    y="jumlah", 
    title="Data Sistem Bahan Bakar"
  )+
  scale_fill_brewer(palette = "Pastel2")+
  theme_light()+
  coord_flip()+
  theme(plot.title = element_text(hjust = 0.5), plot.subtitle = element_text(hjust = 0.5))

a <- a + guides(fill = FALSE)
## Warning: The `<scale>` argument of `guides()` cannot be `FALSE`. Use "none" instead as
## of ggplot2 3.3.4.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
a

data.mobil %>%
  count(fuelsystem) %>%
  mutate(fuelsystem = reorder(fuelsystem, n, .desc = TRUE)) %>%
  ggplot(aes(x = fuelsystem, y = n, fill=fuelsystem))+ 
  geom_bar(stat = "identity", width = 0.8)+
  labs(
    x="sistem bahan bakar", 
    y="jumlah", 
    title="Data Sistem Bahan Bakar"
  )+
  scale_fill_brewer(palette = "Pastel2")+
  theme_light()+
  coord_flip()+
  theme(plot.title = element_text(hjust = 0.5), axis.text.y = element_blank())

Plot alternative dari bar chart adalah lolipop chart. Seperti namanya plot ini terinspirasi dari permen lolipop. Untuk membuat plot ini dibutuhkan dua fungsi yaitu geom_segment dan juga geom_point.

Fungsi geom_segment digunakan untuk menggambarkan garis sedangkan fungsi geom_point digunakan untuk menggambarkan titik.

data.mobil%>%
count(fuelsystem)%>%
  mutate(fuelsystem=reorder(as.factor(fuelsystem),desc(n)))%>%
  ggplot()+
  geom_segment(aes(x=fuelsystem,xend=fuelsystem, y=0, yend=n), color="skyblue", size=1)+
  geom_point(aes(x=fuelsystem,y=n),color="steelblue", size=3)+
    coord_flip() +
    ggtitle("Data Sistem Bahan Bakar") +
    xlab("Sistem Bahan Bakar") +
    ylab("Jumlah") +
    theme(plot.title = element_text(hjust = 0.5))
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

### Plot Sebaran

ggplot(data.mobil) +
  geom_histogram(aes(x = horsepower),fill="orange",col="darkred",binwidth = 20) +
  ggtitle("Histogram Kekuatan Mobil") +
  ylab("Jumlah") +
  xlab("Tenaga") + 
  theme(plot.title = element_text(hjust = 0.5))

### Boxplot

ggplot(data = data.mobil, mapping=aes(x=cylindernumber, y=horsepower, fill=cylindernumber))+
  geom_boxplot(alpha=0.5)+
  theme(legend.position="none")+
  ggtitle ("Tenaga Mobil Berdasarkan Jumlah Silinder")

data.mobil$cylindernumber <- reorder(data.mobil$cylindernumber, data.mobil$horsepower, FUN=median)

ggplot(data = data.mobil, mapping=aes(x=cylindernumber, y=horsepower, fill=cylindernumber))+
  geom_boxplot(alpha=0.5)+
  theme(legend.position="none")+
  ggtitle ("Tenaga Mobil Berdasarkan Jumlah Silinder")

Korelasi

ggplot(data.mobil, aes(x=horsepower, y=highwaympg)) +
  geom_point() +
  geom_smooth(color="red", se=FALSE) +
  theme_classic()
## `geom_smooth()` using method = 'loess' and formula = 'y ~ x'

LATIHAN MINGGU 2

data.2 <- read.csv("D:/ASPRAK VISDAT/StudentsPerformance.csv")
head(data.2)
##   gender race.ethnicity parental.level.of.education        lunch
## 1 female        group B           bachelor's degree     standard
## 2 female        group C                some college     standard
## 3 female        group B             master's degree     standard
## 4   male        group A          associate's degree free/reduced
## 5   male        group C                some college     standard
## 6 female        group B          associate's degree     standard
##   test.preparation.course math.score reading.score writing.score
## 1                    none         72            72            74
## 2               completed         69            90            88
## 3                    none         90            95            93
## 4                    none         47            57            44
## 5                    none         76            78            75
## 6                    none         71            83            78
str(data.2)
## 'data.frame':    1000 obs. of  8 variables:
##  $ gender                     : chr  "female" "female" "female" "male" ...
##  $ race.ethnicity             : chr  "group B" "group C" "group B" "group A" ...
##  $ parental.level.of.education: chr  "bachelor's degree" "some college" "master's degree" "associate's degree" ...
##  $ lunch                      : chr  "standard" "standard" "standard" "free/reduced" ...
##  $ test.preparation.course    : chr  "none" "completed" "none" "none" ...
##  $ math.score                 : int  72 69 90 47 76 71 88 40 64 38 ...
##  $ reading.score              : int  72 90 95 57 78 83 95 43 64 60 ...
##  $ writing.score              : int  74 88 93 44 75 78 92 39 67 50 ...