Grafik Interaktif Menggunakan R

Riki Herliansyah, S.Si., M.Stat

Sabtu, 30 Juli 2021

Highlight

Silahkan install packages berikut jika ingin praktek bersama :)

Beberapa contoh grafik interaktif

Like this

Like this

Like this

And like this

Mengenal interface R

Tampilan R Studio

ggplot()

Beberapa fungsi yang perlu diketahui ketika menggunakan ggplot():

Dan masih banyak lagi :)

ggplot()

Perintah dasar ggplot() adalah:

gg <- ggplot(data, aes(x, y)) 
gg + geom_point()
gg + geom_line()
gg + geom_boxplot()

ggplot()

Sekarang mari kita coba untuk membuat grafik sederhana dengan menggunakan perintah sebelumnya.

library(ggplot2)
gg <- ggplot(mtcars, aes(x=wt, y=mpg)) 
  
gg + geom_point() 

gg + geom_line()

gg + geom_area()

Customize grafik anda!!!

Mudah bukan? :) Selanjutnya, kita akan mengatur tampilan grafik menggunakan beberapa fungsi berikut:

Customize grafik anda!!!

Sekarang coba kita customize grafik berikut:

ToothGrowth$dose <- as.factor(ToothGrowth$dose)
head(ToothGrowth)
##    len supp dose
## 1  4.2   VC  0.5
## 2 11.5   VC  0.5
## 3  7.3   VC  0.5
## 4  5.8   VC  0.5
## 5  6.4   VC  0.5
## 6 10.0   VC  0.5
p <- ggplot(ToothGrowth, aes(x=dose, y=len)) + geom_boxplot()
p

p + ggtitle("Plot of length \n by dose") +
  xlab("Dose (mg)") + ylab("Teeth length")

p <- ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose)) + geom_boxplot()
p + labs(fill = "Dose (mg)") +  xlab("Dose (mg)") + ylab("Teeth length") 

library(viridis)
library(hrbrthemes)
p + scale_fill_viridis(discrete = TRUE, alpha=0.5) +
    geom_jitter(color="black", size=0.6, alpha=0.9) +
    theme_ipsum() +
    theme(
      legend.position="none",
      plot.title = element_text(size=11)
    ) +
    ggtitle("A boxplot with jitter") + xlab("Dose (mg)") + ylab("Teeth length")

library(babynames)
# Load dataset from github
data <- babynames %>% 
  filter(name %in% c("Amanda", "Jessica",    "Patricia", "Deborah",   "Dorothy",  "Helen")) %>%
  filter(sex=="F")


data %>%
  ggplot( aes(x=year, y=n, group=name, color=name)) +
    geom_line() +
    scale_color_viridis(discrete = TRUE) +
    theme(legend.position="none") +
    ggtitle("Popularity of American names in the previous 30 years") +
    theme_ipsum()

Customize grafik anda!!!

Sekarang kita akan mencoba menambah teks pada grafik. Kita akan menggunakan data konsumsi bahan bakar pada contoh sebelumnya.

library(tidyverse)

p <- ggplot(mtcars, aes(x=wt, y=mpg)) +
  geom_point()  

rownames(mtcars)
##  [1] "Mazda RX4"           "Mazda RX4 Wag"       "Datsun 710"         
##  [4] "Hornet 4 Drive"      "Hornet Sportabout"   "Valiant"            
##  [7] "Duster 360"          "Merc 240D"           "Merc 230"           
## [10] "Merc 280"            "Merc 280C"           "Merc 450SE"         
## [13] "Merc 450SL"          "Merc 450SLC"         "Cadillac Fleetwood" 
## [16] "Lincoln Continental" "Chrysler Imperial"   "Fiat 128"           
## [19] "Honda Civic"         "Toyota Corolla"      "Toyota Corona"      
## [22] "Dodge Challenger"    "AMC Javelin"         "Camaro Z28"         
## [25] "Pontiac Firebird"    "Fiat X1-9"           "Porsche 914-2"      
## [28] "Lotus Europa"        "Ford Pantera L"      "Ferrari Dino"       
## [31] "Maserati Bora"       "Volvo 142E"
p +  geom_text(
    label=rownames(mtcars), 
    nudge_x = 0.25, nudge_y = 0.25, 
    check_overlap = T
  )

p + geom_label(
    label=rownames(mtcars), 
    nudge_x = 0.25, nudge_y = 0.25, 
    check_overlap = T
  )

p + geom_label(
    label="Look at this!", 
    x=4.1,
    y=20,
    label.padding = unit(0.55, "lines"), # Rectangle size around label
    label.size = 0.35,
    color = "black",
    fill="#69b3a2"
  )

datacars <- mtcars %>%
  rownames_to_column(var="carName")
p + geom_label( 
    data=datacars %>% filter(mpg>20 & wt>3), # Filter data first
    aes(label=carName)
  )

Customize grafik anda!!!

Sekarang kita akan menggabungkan beberapa grafik dalam satu frame dengan menggunakan fungsi face_wrap() atau menggunakan gridExtra()

# Split by columns (default)
ggplot( mtcars , aes(x=mpg, y=wt, color=as.factor(cyl) )) + 
  geom_point(size=3) +  
  facet_wrap(~cyl) +
  theme(legend.position="none")

# Split by row
ggplot( mtcars , aes(x=mpg, y=wt, color=as.factor(cyl)  )) + 
  geom_point(size=3) +  
  facet_wrap(~cyl , dir="v")  +
  theme(legend.position="none")

# Add label at the bottom
ggplot( mtcars , aes(x=mpg, y=wt, color=as.factor(cyl)  )) + 
  geom_point(size=3) +  
  facet_wrap(~cyl , strip.position="bottom") +
  theme(legend.position="none")

ggplot( mtcars , aes(x=mpg, y=wt )) + 
  geom_point() +
  facet_grid( cyl ~ gear)

data %>%
  ggplot( aes(x=year, y=n, group=name, fill=name)) +
    geom_area() +
    scale_fill_viridis(discrete = TRUE) +
    theme(legend.position="none") +
    ggtitle("Popularity of American names in the previous 30 years") +
    theme_ipsum() +
    theme(
      legend.position="none",
      panel.spacing = unit(0.1, "lines"),
      strip.text.x = element_text(size = 8)
    ) +
    facet_wrap(~name, scale="free_y")

Customize grafik anda!!!

library(gridExtra)
# Make 3 simple graphics:
g1 <- ggplot(mtcars, aes(x=qsec)) + geom_density(fill="slateblue")
g2 <- ggplot(mtcars, aes(x=drat, y=qsec, color=cyl)) + geom_point(size=5) + theme(legend.position="none")
g3 <- ggplot(mtcars, aes(x=factor(cyl), y=qsec, fill=cyl)) + geom_boxplot() + theme(legend.position="none")
g4 <- ggplot(mtcars , aes(x=factor(cyl), fill=factor(cyl))) +  geom_bar()
 
# Plots
grid.arrange(g2, arrangeGrob(g3, g4, ncol=2), nrow = 2)

grid.arrange(g1, g2, g3, nrow = 3)

grid.arrange(g2, arrangeGrob(g3, g4, ncol=2), nrow = 1)

plotly()

library(plotly)

# Load dataset from github
data <- read.table("https://raw.githubusercontent.com/holtzy/data_to_viz/master/Example_dataset/3_TwoNumOrdered.csv", header=T)
data$date <- as.Date(data$date)

# Usual area chart
p <- data %>%
  ggplot( aes(x=date, y=value)) +
    geom_area(fill="#69b3a2", alpha=0.5) +
    geom_line(color="#69b3a2") +
    ylab("bitcoin price ($)") +
    theme_ipsum()

# Turn it interactive with ggplotly
ggplotly(p)
data = head(mtcars, 30)
p2 <- ggplot(data, aes(x=wt, y=mpg)) +
  geom_point() 
ggplotly(p2)
# Plot
data <- babynames %>% 
  filter(name %in% c("Amanda", "Jessica",    "Patricia", "Deborah",   "Dorothy",  "Helen")) %>%
  filter(sex=="F")

p3 <- data %>% 
  ggplot( aes(x=year, y=n, fill=name, text=name)) +
    geom_area( ) +
    scale_fill_viridis(discrete = TRUE) +
    theme(legend.position="none") +
    ggtitle("Popularity of American names in the previous 30 years") +
    theme_ipsum() +
    theme(legend.position="none")
ggplotly(p3, tooltip="text")

Contoh lagi untuk plotly()

p <- gapminder %>%
  filter(year==1977) %>%
  ggplot( aes(gdpPercap, lifeExp, size = pop, color=continent)) +
  geom_point() +
  theme_bw()

ggplotly(p)

Penutup

TERIMA KASIH

<>