U.UNIQUE / PRACTICUM NOTESSTATISTICS & DATA SCIENCE
IPB UNIVERSITYPRACTICUM 03
Daftar IsiTable of Contents

Data Visualization

Grammar of Graphics · ggplot2 · plotly

Grafik yang baik membantu menjawab pertanyaan analisis dengan memperlihatkan distribusi, perbandingan, hubungan, waktu atau pola spasial. Pada praktikum ini kita membangun visualisasi dari beberapa dataset bawaan R dengan ggplot2.A good chart answers an analytical question by revealing distributions, comparisons, relationships, time patterns or spatial patterns. In this practicum we build visualizations from R package datasets using ggplot2.

Gunakan kode secara berurutan; perhatikan bagaimana pilihan geom dan pemetaan estetika mengubah informasi yang terbaca. Jalankan bagian plotly di RStudio untuk memperoleh interaksi asli.Run the code in sequence; observe how geoms and aesthetic mappings change the information conveyed. Run the plotly section in RStudio for its original interactivity.

Tujuan praktikum adalah memilih grafik sesuai pertanyaan, membangun layer dengan benar, membandingkan representasi, dan menjelaskan temuan tanpa mengubah data demi tampilan. Setelah itu, simpan grafik dan kerjakan latihan mandiri.The objectives are to select plots for analytical questions, build layers correctly, compare representations, and explain findings without manipulating data for appearance. Then export plots and complete the independent exercises.

Persiapan packagePackage Preparation

Siapkan package sebelum menggambar.Prepare the packages before plotting.

Pada praktikum ini digunakan beberapa package untuk membantu proses pengolahan dan visualisasi data.

Apabila package belum tersedia, package dapat diinstal melalui Console RStudio menggunakan sintaks berikut.

R
install.packages(c("tidyverse",
                   "ggpubr",
                   "ggridges",
                   "GGally",
                   "plotly",
                   "maps"),
                 repos = "https://cloud.r-project.org",
                 dependencies = TRUE)

Setelah package berhasil diinstal, package dapat dipanggil menggunakan sintaks berikut.

R
library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.2.1     ✔ readr     2.2.0
✔ forcats   1.0.1     ✔ stringr   1.6.0
✔ ggplot2   4.0.3     ✔ tibble    3.3.1
✔ lubridate 1.9.5     ✔ tidyr     1.3.2
✔ purrr     1.2.2
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become
errors

In this practicum, several packages are used to support data processing and data visualization.

If the packages are not yet available, they can be installed through the RStudio Console using the following syntax.

R
install.packages(c("tidyverse",
                   "ggpubr",
                   "ggridges",
                   "GGally",
                   "plotly",
                   "maps"),
                 repos = "https://cloud.r-project.org",
                 dependencies = TRUE)

After the packages have been successfully installed, they can be loaded using the following syntax.

R
library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.2.1     ✔ readr     2.2.0
✔ forcats   1.0.1     ✔ stringr   1.6.0
✔ ggplot2   4.0.3     ✔ tibble    3.3.1
✔ lubridate 1.9.5     ✔ tidyr     1.3.2
✔ purrr     1.2.2
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become
errors

Package untuk penyesuaian grafikPackages for plot customization

Untuk bagian anotasi, gunakan ggrepel agar label observasi dapat dijauhkan dari titik dan label lain. Semua fungsi ggplot2 tersedia melalui tidyverse. Package maps menyediakan batas wilayah; plotly menyediakan konversi grafik interaktif. Jalankan instalasi hanya jika paket belum tersedia.For annotations, ggrepel helps separate observation labels from points and other labels. All ggplot2 functions are available through tidyverse. maps supplies geographic boundaries; plotly converts plots into interactive charts. Install packages only if missing.

R
install.packages("ggrepel")

Fungsi dipanggil melalui namespace ggrepel::geom_text_repel(), sehingga library tambahan tidak wajib.Call ggrepel::geom_text_repel() by namespace; attaching the package is optional.

Jalankan kode ini di RStudio untuk melihat hasil R.Run this code in RStudio to obtain the R output.

Pengenalan dataData Understanding

Kenali tipe dan dimensi data agar pemetaan variabel ke grafik tepat.Inspect variable types and dimensions before mapping variables to plots.

Pada praktikum kali ini digunakan beberapa dataset untuk mengilustrasikan berbagai jenis visualisasi data. Dataset dipilih berdasarkan karakteristik variabel dan tujuan visualisasi yang akan dipelajari.

Data yang digunakan pada praktikum ini adalah:

mpg diamonds economics data peta negara bagian Amerika Serikat

Sebagian besar dataset telah tersedia pada package yang digunakan sehingga tidak diperlukan proses import data dari file eksternal.

Data mpg

Dataset mpg merupakan salah satu dataset yang tersedia pada package ggplot2 . Dataset ini berisi informasi mengenai karakteristik sejumlah kendaraan, seperti kapasitas mesin, jumlah silinder, jenis sistem penggerak, jenis kendaraan, serta efisiensi penggunaan bahan bakar.

Dataset ini digunakan untuk mengilustrasikan visualisasi perbandingan antar-kategori serta hubungan antara beberapa variabel.

R
glimpse(mpg)
Rows: 234
Columns: 11
$ manufacturer <chr> "audi", "audi", "audi", "audi", "audi", "audi", "audi", "…
$ model        <chr> "a4", "a4", "a4", "a4", "a4", "a4", "a4", "a4 quattro", "…
$ displ        <dbl> 1.8, 1.8, 2.0, 2.0, 2.8, 2.8, 3.1, 1.8, 1.8, 2.0, 2.0, 2.…
$ year         <int> 1999, 1999, 2008, 2008, 1999, 1999, 2008, 1999, 1999, 200…
$ cyl          <int> 4, 4, 4, 4, 6, 6, 6, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6, 8, 8, …
$ trans        <chr> "auto(l5)", "manual(m5)", "manual(m6)", "auto(av)", "auto…
$ drv          <chr> "f", "f", "f", "f", "f", "f", "f", "4", "4", "4", "4", "4…
$ cty          <int> 18, 21, 20, 21, 16, 18, 18, 18, 16, 20, 19, 15, 17, 17, 1…
$ hwy          <int> 29, 29, 31, 30, 26, 26, 27, 26, 25, 28, 27, 25, 25, 25, 2…
$ fl           <chr> "p", "p", "p", "p", "p", "p", "p", "p", "p", "p", "p", "p…
$ class        <chr> "compact", "compact", "compact", "compact", "compact", "c…

Beberapa variabel yang akan digunakan antara lain:

manufacturer : produsen kendaraan displ : kapasitas mesin dalam liter cyl : jumlah silinder drv : jenis sistem penggerak kendaraan cty : efisiensi bahan bakar di dalam kota hwy : efisiensi bahan bakar di jalan raya class : kelas atau jenis kendaraan

Data diamonds

Dataset diamonds juga tersedia pada package ggplot2 . Dataset ini berisi informasi mengenai karakteristik berlian, antara lain harga, berat berlian (carat), kualitas potongan (cut), warna (color), dan tingkat kejernihan (clarity).

Dataset ini terutama digunakan untuk mengilustrasikan visualisasi distribusi serta hubungan antara variabel numerik dan kategorik.

R
glimpse(diamonds)
Rows: 53,940
Columns: 10
$ carat   <dbl> 0.23, 0.21, 0.23, 0.29, 0.31, 0.24, 0.24, 0.26, 0.22, 0.23, 0.…
$ cut     <ord> Ideal, Premium, Good, Premium, Good, Very Good, Very Good, Ver…
$ color   <ord> E, E, E, I, J, J, I, H, E, H, J, J, F, J, E, E, I, J, J, J, I,…
$ clarity <ord> SI2, SI1, VS1, VS2, SI2, VVS2, VVS1, SI1, VS2, VS1, SI1, VS1, …
$ depth   <dbl> 61.5, 59.8, 56.9, 62.4, 63.3, 62.8, 62.3, 61.9, 65.1, 59.4, 64…
$ table   <dbl> 55, 61, 65, 58, 58, 57, 57, 55, 61, 61, 55, 56, 61, 54, 62, 58…
$ price   <int> 326, 326, 327, 334, 335, 336, 336, 337, 337, 338, 339, 340, 34…
$ x       <dbl> 3.95, 3.89, 4.05, 4.20, 4.34, 3.94, 3.95, 4.07, 3.87, 4.00, 4.…
$ y       <dbl> 3.98, 3.84, 4.07, 4.23, 4.35, 3.96, 3.98, 4.11, 3.78, 4.05, 4.…
$ z       <dbl> 2.43, 2.31, 2.31, 2.63, 2.75, 2.48, 2.47, 2.53, 2.49, 2.39, 2.…

Dataset diamonds memiliki jumlah observasi yang relatif besar. Pada visualisasi yang melibatkan banyak titik pengamatan, seperti scatter plot, sebagian observasi akan diambil sebagai sampel agar pola pada grafik lebih mudah diamati dan mengurangi penumpukan titik (overplotting).

R
set.seed(123)

Catatan: Pengambilan sampel hanya digunakan pada visualisasi tertentu. Untuk visualisasi distribusi atau perhitungan jumlah observasi, tetap digunakan keseluruhan data jika diperlukan.

Data economics

Dataset economics merupakan data deret waktu (time series) yang tersedia pada package ggplot2 . Dataset ini berisi beberapa indikator ekonomi yang dicatat berdasarkan waktu.

Dataset ini digunakan untuk mempelajari visualisasi perubahan nilai dari waktu ke waktu menggunakan line chart dan area chart.

R
glimpse(economics)
Rows: 574
Columns: 6
$ date     <date> 1967-07-01, 1967-08-01, 1967-09-01, 1967-10-01, 1967-11-01, …
$ pce      <dbl> 506.7, 509.8, 515.6, 512.2, 517.4, 525.1, 530.9, 533.6, 544.3…
$ pop      <dbl> 198712, 198911, 199113, 199311, 199498, 199657, 199808, 19992…
$ psavert  <dbl> 12.6, 12.6, 11.9, 12.9, 12.8, 11.8, 11.7, 12.3, 11.7, 12.3, 1…
$ uempmed  <dbl> 4.5, 4.7, 4.6, 4.9, 4.7, 4.8, 5.1, 4.5, 4.1, 4.6, 4.4, 4.4, 4…
$ unemploy <dbl> 2944, 2945, 2958, 3143, 3066, 3018, 2878, 3001, 2877, 2709, 2…

Beberapa variabel yang tersedia antara lain:

date : waktu pengamatan pce : personal consumption expenditures pop : jumlah populasi psavert : personal savings rate uempmed : median durasi pengangguran unemploy : jumlah pengangguran

Data Peta

Untuk mengilustrasikan visualisasi geospasial, digunakan data koordinat batas negara bagian Amerika Serikat yang diperoleh dari package maps .

Data peta dapat dipanggil menggunakan fungsi map_data() sebagai berikut.

R
us_states <- map_data("state")

Data tersebut berisi koordinat yang membentuk poligon setiap wilayah, sehingga dapat divisualisasikan menggunakan ggplot2 .

In this practicum, several datasets are used to illustrate different types of data visualization. The datasets are selected based on the characteristics of the variables and the visualization objectives to be studied.

The datasets used in this practicum are:

mpg diamonds economics map data of the United States

Most of the datasets are already available in the packages used, so there is no need to import data from external files.

Data mpg

The mpg dataset is one of the datasets available in the ggplot2 package. This dataset contains information about the characteristics of several vehicles, such as engine displacement, number of cylinders, type of drive system, vehicle class, and fuel efficiency.

This dataset is used to illustrate comparisons across categories and relationships between several variables.

R
glimpse(mpg)
Rows: 234
Columns: 11
$ manufacturer <chr> "audi", "audi", "audi", "audi", "audi", "audi", "audi", "…
$ model        <chr> "a4", "a4", "a4", "a4", "a4", "a4", "a4", "a4 quattro", "…
$ displ        <dbl> 1.8, 1.8, 2.0, 2.0, 2.8, 2.8, 3.1, 1.8, 1.8, 2.0, 2.0, 2.…
$ year         <int> 1999, 1999, 2008, 2008, 1999, 1999, 2008, 1999, 1999, 200…
$ cyl          <int> 4, 4, 4, 4, 6, 6, 6, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6, 8, 8, …
$ trans        <chr> "auto(l5)", "manual(m5)", "manual(m6)", "auto(av)", "auto…
$ drv          <chr> "f", "f", "f", "f", "f", "f", "f", "4", "4", "4", "4", "4…
$ cty          <int> 18, 21, 20, 21, 16, 18, 18, 18, 16, 20, 19, 15, 17, 17, 1…
$ hwy          <int> 29, 29, 31, 30, 26, 26, 27, 26, 25, 28, 27, 25, 25, 25, 2…
$ fl           <chr> "p", "p", "p", "p", "p", "p", "p", "p", "p", "p", "p", "p…
$ class        <chr> "compact", "compact", "compact", "compact", "compact", "c…

Several variables that will be used include:

manufacturer : vehicle manufacturer displ : engine displacement in liters cyl : number of cylinders drv : type of vehicle drive system cty : city fuel efficiency hwy : highway fuel efficiency class : vehicle class or type

Data diamonds

The diamonds dataset is also available in the ggplot2 package. This dataset contains information about diamond characteristics, including price, diamond weight ( carat ), cut quality ( cut ), color ( color ), and clarity ( clarity ).

This dataset is mainly used to illustrate distribution visualization and relationships between numerical and categorical variables.

R
glimpse(diamonds)
Rows: 53,940
Columns: 10
$ carat   <dbl> 0.23, 0.21, 0.23, 0.29, 0.31, 0.24, 0.24, 0.26, 0.22, 0.23, 0.…
$ cut     <ord> Ideal, Premium, Good, Premium, Good, Very Good, Very Good, Ver…
$ color   <ord> E, E, E, I, J, J, I, H, E, H, J, J, F, J, E, E, I, J, J, J, I,…
$ clarity <ord> SI2, SI1, VS1, VS2, SI2, VVS2, VVS1, SI1, VS2, VS1, SI1, VS1, …
$ depth   <dbl> 61.5, 59.8, 56.9, 62.4, 63.3, 62.8, 62.3, 61.9, 65.1, 59.4, 64…
$ table   <dbl> 55, 61, 65, 58, 58, 57, 57, 55, 61, 61, 55, 56, 61, 54, 62, 58…
$ price   <int> 326, 326, 327, 334, 335, 336, 336, 337, 337, 338, 339, 340, 34…
$ x       <dbl> 3.95, 3.89, 4.05, 4.20, 4.34, 3.94, 3.95, 4.07, 3.87, 4.00, 4.…
$ y       <dbl> 3.98, 3.84, 4.07, 4.23, 4.35, 3.96, 3.98, 4.11, 3.78, 4.05, 4.…
$ z       <dbl> 2.43, 2.31, 2.31, 2.63, 2.75, 2.48, 2.47, 2.53, 2.49, 2.39, 2.…

The diamonds dataset contains a relatively large number of observations. For visualizations involving many data points, such as scatter plots, a sample of observations will be used so that patterns in the graph are easier to observe and point overlap (overplotting) can be reduced.

R
set.seed(123)

Note: Sampling is only used for certain visualizations. For distribution visualizations or calculations involving the number of observations, the complete dataset will still be used when necessary.

Data economics

The economics dataset is a time series dataset available in the ggplot2 package. This dataset contains several economic indicators recorded over time.

This dataset is used to study changes in values over time using line charts and area charts.

R
glimpse(economics)
Rows: 574
Columns: 6
$ date     <date> 1967-07-01, 1967-08-01, 1967-09-01, 1967-10-01, 1967-11-01, …
$ pce      <dbl> 506.7, 509.8, 515.6, 512.2, 517.4, 525.1, 530.9, 533.6, 544.3…
$ pop      <dbl> 198712, 198911, 199113, 199311, 199498, 199657, 199808, 19992…
$ psavert  <dbl> 12.6, 12.6, 11.9, 12.9, 12.8, 11.8, 11.7, 12.3, 11.7, 12.3, 1…
$ uempmed  <dbl> 4.5, 4.7, 4.6, 4.9, 4.7, 4.8, 5.1, 4.5, 4.1, 4.6, 4.4, 4.4, 4…
$ unemploy <dbl> 2944, 2945, 2958, 3143, 3066, 3018, 2878, 3001, 2877, 2709, 2…

Several available variables include:

date : observation date pce : personal consumption expenditures pop : population psavert : personal savings rate uempmed : median duration of unemployment unemploy : number of unemployed people

Map Data

To illustrate geospatial visualization, coordinate data representing the boundaries of the United States are obtained from the maps package.

The map data can be accessed using the map_data() function as follows.

R
us_states <- map_data("state")

The data contain coordinates that form polygons for each region, allowing them to be visualized using

ggplot2 .

Perhatikan unit: cty dan hwy dalam miles per gallon (nilai lebih besar menunjukkan penggunaan bahan bakar lebih efisien), displ dalam liter, price dalam USD, serta unemploy dalam ribuan orang. Data contoh browser mpg dan diamonds berasal dari salinan dataset ggplot2 yang didistribusikan bersama plotnine; hasil grafik R yang sudah tersedia tetap mengikuti render materi.Note the units: cty and hwy are miles per gallon (higher is more fuel-efficient), displ is in liters, price in USD, and unemploy in thousands of people. Browser examples use the copies of ggplot2 mpg and diamonds datasets distributed with plotnine; existing R charts retain their original rendered results.

Membangun grafik dengan ggplot2Building a Plot with ggplot2

Mulai dengan data, pemetaan estetika, dan geom; tambahkan komponen secara bertahap.Start with data, aesthetic mappings and a geom; add components gradually.

Di dalam R terdapat beberapa package yang dapat digunakan untuk membuat visualisasi data. Pada praktikum kali ini kita akan berfokus pada penggunaan package ggplot2 yang merupakan bagian dari

tidyverse .

Package ggplot2 membangun suatu grafik dari beberapa komponen yang dapat ditambahkan secara bertahap. Secara sederhana, struktur umum pembuatan grafik dengan ggplot2 adalah sebagai berikut.

Skema sintaks (bukan kode yang dapat dijalankan langsung). Ganti DATA, X, Y, dan geom dengan nama yang sesuai.Syntax template (not directly executable). Replace DATA, X, Y and geom with actual names.

R
ggplot(data = DATA, aes(x = X, y = Y)) +
  geom_...()

Sintaks di atas merupakan bentuk umum. DATA menunjukkan dataset yang digunakan, sedangkan X dan Y menunjukkan variabel yang akan divisualisasikan. Bentuk geom_...() kemudian disesuaikan dengan jenis grafik yang ingin dibuat.

Sebagai ilustrasi, kita akan menggunakan data mpg untuk melihat hubungan antara kapasitas mesin ( displ ) dengan efisiensi bahan bakar di jalan raya ( hwy ).

R
ggplot(data = mpg,
       aes(x = displ, y = hwy)) +
  geom_point()
R output figure

Pada sintaks di atas, argumen data digunakan untuk menentukan dataset yang akan divisualisasikan. Fungsi aes() digunakan untuk menentukan variabel yang akan ditampilkan pada grafik. Variabel displ ditempatkan pada sumbu horizontal dan variabel hwy ditempatkan pada sumbu vertikal.

Fungsi geom_point() digunakan untuk menampilkan setiap observasi dalam bentuk titik. Grafik seperti ini disebut sebagai diagram pencar (scatter plot).

Kemudian kita dapat menambahkan informasi lain seperti judul grafik, label sumbu, dan tema.

R
ggplot(data = mpg,
       aes(x = displ, y = hwy)) +
  geom_point() +
  labs(
    title = "Hubungan Kapasitas Mesin dan Efisiensi Bahan Bakar",
    x = "Kapasitas mesin (liter)",
    y = "Efisiensi bahan bakar jalan raya (mpg)"
  ) +
  theme_minimal()
R output figure

Fungsi labs() digunakan untuk memberikan judul dan label sumbu pada grafik. Sementara itu,

theme_minimal()  digunakan untuk mengubah tampilan grafik menjadi lebih sederhana.

Komponen-komponen tersebut dapat ditambahkan atau dimodifikasi sesuai dengan informasi yang ingin ditampilkan.

There are several packages in R that can be used to create data visualizations. In this practicum, we will focus on using the ggplot2 package, which is part of the tidyverse . The ggplot2 package builds a graph from several components that can be added gradually. In general, the basic structure for creating a graph using ggplot2 is as follows.

Skema sintaks (bukan kode yang dapat dijalankan langsung). Ganti DATA, X, Y, dan geom dengan nama yang sesuai.Syntax template (not directly executable). Replace DATA, X, Y and geom with actual names.

R
ggplot(data = DATA, aes(x = X, y = Y)) +
  geom_...()

The syntax above represents a general form. DATA indicates the dataset being used, while X and Y indicate the variables to be visualized. The geom_...() component is then adjusted according to the type of graph to be created.

As an illustration, we will use the mpg dataset to examine the relationship between engine displacement ( displ ) and highway fuel efficiency ( hwy ).

R
ggplot(data = mpg,
       aes(x = displ, y = hwy)) +
  geom_point()
R output figure

In the syntax above, the data argument is used to specify the dataset to be visualized. The aes() function is used to specify the variables to be displayed in the graph. The displ variable is placed on the horizontal axis, while the hwy variable is placed on the vertical axis.

The geom_point() function is used to display each observation as a point. This type of graph is called a scatter plot.

We can then add other information such as a graph title, axis labels, and a theme.

R
ggplot(data = mpg,
       aes(x = displ, y = hwy)) +
  geom_point() +
  labs(
    title = "Relationship Between Engine Displacement and Fuel Efficiency",
    x = "Engine displacement (liters)",
    y = "Highway fuel efficiency (mpg)"
  ) +
  theme_minimal()
R output figure

The labs() function is used to add a title and axis labels to the graph. Meanwhile, theme_minimal() is used to make the appearance of the graph simpler.

These components can be added or modified according to the information that needs to be displayed.

Membangun layer secara bertahapBuilding a plot layer by layer

Data menentukan observasi, aes() menentukan variabel yang dipetakan, geom menentukan bentuk tanda visual, labs() memberikan konteks, dan theme mengatur unsur non-data. Tanda + menambahkan komponen pada objek ggplot yang sama. Tanpa geom, pemetaan sudah terdefinisi tetapi observasi belum digambar.Data determines the observations, aes() maps variables, geom determines visual marks, labs() provides context, and theme controls non-data elements. The + operator adds components to the same ggplot object. Without a geom the mapping exists but observations are not drawn.

1. DataPilih datasetChoose a datasetggplot(mpg)
2. AestheticsPeta variabelMap variablesaes(displ, hwy)
3. GeometryTanda visualVisual marksgeom_point()
4. LabelsKonteksContextlabs(...)
5. ThemeTampilanAppearancetheme_minimal()
INTERACTIVE LAB

Layer BuilderLayer Builder

Tambahkan layer secara bertahap hingga grafik mempunyai judul, unit dan tema.Add layers progressively until the plot has a title, units and theme.

R
# Interactive R example

Bandingkan tahap 1–4. Posisi observasi tidak berubah setelah geom ditambahkan; labels dan theme hanya memperjelas informasi.Compare stages 1–4. Observation positions do not change after adding the geom; labels and theme only clarify the information.

Data mpg (234 observasi); grafik dihitung di browser, bukan output render R.mpg data (234 observations); chart computed in the browser, not rendered R output.

Elemen visual dan pemetaan estetikaVisual Elements and Aesthetic Mapping

Posisi, bentuk, garis, ukuran dan warna menyampaikan informasi yang berbeda. Uji bagaimana tiap pemetaan mengubah pesan grafik.Position, shape, line, size and color encode different information. Explore how each mapping changes the plot’s message.

Dalam suatu grafik, nilai atau karakteristik suatu variabel dapat ditampilkan melalui beberapa elemen visual. Beberapa elemen visual yang umum digunakan adalah posisi, simbol, garis, ukuran, dan warna.

Pada bagian ini kita akan melihat bagaimana elemen-elemen tersebut digunakan di dalam ggplot2 .

Posisi

Posisi digunakan untuk menunjukkan nilai suatu observasi berdasarkan letaknya pada grafik.

Sebagai ilustrasi, digunakan kembali variabel displ dan hwy dari data mpg .

R
ggplot(data = mpg,
       aes(x = displ,
           y = hwy)) +
  geom_point()
R output figure

Pada grafik di atas, nilai displ ditampilkan berdasarkan posisi horizontal, sedangkan nilai hwy ditampilkan berdasarkan posisi vertikal.

Dari pola titik yang terbentuk dapat terlihat bahwa kendaraan dengan kapasitas mesin yang lebih besar cenderung memiliki efisiensi bahan bakar di jalan raya yang lebih rendah.

Simbol

Selain posisi, bentuk simbol dapat digunakan untuk membedakan kelompok pada data. Pada ggplot2 , bentuk simbol diatur menggunakan shape .

Sebagai ilustrasi, digunakan variabel drv yang menunjukkan sistem penggerak kendaraan.

R
ggplot(data = mpg,
       aes(x = displ,
           y = hwy,
           shape = drv)) +
  geom_point(size = 2.5)
R output figure

Pada sintaks di atas, variabel drv dimasukkan ke dalam shape . Dengan demikian, setiap kategori pada

drv  akan ditampilkan menggunakan bentuk titik yang berbeda.

Penggunaan bentuk simbol lebih sesuai digunakan untuk membedakan variabel kategorik karena bentuk tidak menunjukkan urutan tertentu.

Garis

Garis digunakan untuk menghubungkan beberapa pengamatan. Elemen ini sering digunakan ketika pengamatan mempunyai urutan tertentu, misalnya berdasarkan waktu.

Sebagai ilustrasi, kita akan menggunakan data economics .

R
ggplot(data = economics,
       aes(x = date,
           y = unemploy)) +
  geom_line()
R output figure

Pada grafik di atas, fungsi geom_line() menghubungkan nilai unemploy berdasarkan urutan pada variabel date .

Dengan menggunakan garis, perubahan nilai dari satu waktu ke waktu berikutnya dapat diamati dengan lebih mudah.

Ukuran

Ukuran suatu objek pada grafik juga dapat digunakan untuk menunjukkan besar kecilnya nilai suatu variabel.

Sebagai ilustrasi, digunakan jumlah silinder kendaraan ( cyl ).

R
ggplot(data = mpg,
       aes(x = displ,
           y = hwy,
           size = cyl)) +
  geom_point(alpha = 0.6)
R output figure

Pada sintaks di atas, variabel cyl dimasukkan ke dalam size . Semakin besar nilai cyl , semakin besar pula ukuran titik yang ditampilkan.

Warna

Warna dapat digunakan untuk membedakan kelompok maupun menunjukkan besar kecilnya suatu nilai.

Sebagai contoh, variabel drv digunakan untuk memberikan warna yang berbeda pada masing-masing sistem penggerak kendaraan.

R
ggplot(data = mpg,
       aes(x = displ,
           y = hwy,
           color = drv)) +
  geom_point(size = 2.5)
R output figure

Pada sintaks di atas, variabel drv dimasukkan ke dalam color . Oleh karena itu, setiap kategori pada variabel tersebut akan ditampilkan menggunakan warna yang berbeda.

Jika variabel yang digunakan berupa numerik, ggplot2 akan menampilkan warna dalam bentuk gradasi untuk menunjukkan perubahan nilai.

Menggabungkan Elemen Visual

Beberapa elemen visual dapat digunakan secara bersamaan dalam satu grafik.

R
ggplot(data = mpg,
       aes(x = displ,
           y = hwy,
           color = drv,
           shape = drv,
           size = cyl)) +
  geom_point(alpha = 0.7)
R output figure

Pada grafik di atas, posisi menunjukkan nilai displ dan hwy , warna dan bentuk menunjukkan sistem penggerak kendaraan, sedangkan ukuran titik menunjukkan jumlah silinder.

Meskipun beberapa informasi dapat ditampilkan dalam satu grafik, terlalu banyak elemen visual dapat menyebabkan grafik menjadi lebih sulit dibaca. Oleh karena itu, elemen visual yang digunakan sebaiknya disesuaikan dengan informasi yang ingin ditampilkan.

In a graph, the value or characteristics of a variable can be represented through several visual elements. Commonly used visual elements include position, symbol, line, size, and color.

In this section, we will examine how these elements are used in ggplot2 .

Position

Position is used to represent the value of an observation based on its location in the graph. As an illustration, the displ and hwy variables from the mpg dataset are used again.

R
ggplot(data = mpg,
       aes(x = displ,
           y = hwy)) +
  geom_point()
R output figure

In the graph above, the value of displ is represented by the horizontal position, while the value of hwy is represented by the vertical position.

From the pattern of points, it can be seen that vehicles with larger engine displacement tend to have lower highway fuel efficiency.

Symbol

In addition to position, symbol shape can be used to distinguish groups in the data. In ggplot2 , symbol shape is controlled using shape .

As an illustration, the drv variable is used to represent the vehicle drive system.

R
ggplot(data = mpg,
       aes(x = displ,
           y = hwy,
           shape = drv)) +
  geom_point(size = 2.5)
R output figure

In the syntax above, the drv variable is mapped to shape . Therefore, each category in drv is represented using a different point shape.

Symbol shape is more appropriate for distinguishing categorical variables because shape does not indicate a particular order.

Line

Lines are used to connect several observations. This element is often used when observations have a specific order, for example, according to time.

As an illustration, we will use the economics dataset.

R
ggplot(data = economics,
       aes(x = date,
           y = unemploy)) +
  geom_line()
R output figure

In the graph above, the geom_line() function connects the values of unemploy according to the order of the date variable.

By using a line, changes in values from one time point to another can be observed more easily.

Size

The size of an object in a graph can also be used to represent the magnitude of a variable.

As an illustration, the number of vehicle cylinders ( cyl ) is used.

R
ggplot(data = mpg,
       aes(x = displ,
           y = hwy,
           size = cyl)) +
  geom_point(alpha = 0.6)
R output figure

In the syntax above, the cyl variable is mapped to size . The larger the value of cyl , the larger the point displayed in the graph.

Color

Color can be used to distinguish groups or represent the magnitude of a value.

As an example, the drv variable is used to assign different colors to each vehicle drive system.

R
ggplot(data = mpg,
       aes(x = displ,
           y = hwy,
           color = drv)) +
  geom_point(size = 2.5)
R output figure

In the syntax above, the drv variable is mapped to color . Therefore, each category of the variable is displayed using a different color.

If the variable is numerical, ggplot2 will display colors as a gradient to represent changes in value.

Combining Visual Elements

Several visual elements can be used simultaneously in one graph.

R
ggplot(data = mpg,
       aes(x = displ,
           y = hwy,
           color = drv,
           shape = drv,
           size = cyl)) +
  geom_point(alpha = 0.7)
R output figure

In the graph above, position represents the values of displ and hwy , color and shape represent the vehicle drive system, while point size represents the number of cylinders.

Although several types of information can be displayed in one graph, using too many visual elements can make the graph more difficult to read. Therefore, the visual elements used should be adjusted according to the information that needs to be displayed.

Mapping dan settingMapping and setting

Pemetaan di dalam aes() menghubungkan nilai kolom dengan sifat visual dan biasanya menghasilkan skala serta legenda. Pengaturan di luar aes() menetapkan satu sifat untuk semua observasi. Color mengatur garis atau tepi, fill mengatur isian (misalnya batang, poligon, atau titik shape 21–25); alpha mengatur transparansi, linetype pola garis, dan linewidth ketebalannya. Size lebih tepat untuk ukuran titik.Mapping inside aes() connects column values to visual properties and usually creates a scale and legend. Setting outside aes() assigns one property to all observations. Color controls strokes or outlines, fill controls interiors (bars, polygons, or shapes 21–25); alpha controls opacity, linetype controls line pattern, and linewidth controls thickness. Size is more appropriate for point size.

INTERACTIVE LAB

Aesthetic Mapping LaboratoryAesthetic Mapping Laboratory

Bandingkan warna tetap, warna berdasarkan drv, serta kombinasi warna dan bentuk.Compare fixed color, color mapped to drv, and color plus shape.

R
# Interactive R example

Legenda merepresentasikan pemetaan variabel, bukan sekadar hiasan. Alpha kecil membantu mengungkap penumpukan titik; memperbesar titik dapat justru memperburuknya.The legend represents a variable mapping, not decoration. Low alpha helps expose overlapping points; increasing size can make overlap worse.

Data mpg (234 observasi); grafik dihitung di browser, bukan output render R.mpg data (234 observations); chart computed in the browser, not rendered R output.

R
ggplot(mpg, aes(displ, hwy, fill = drv)) +
  geom_point(shape = 21, color = "grey30", size = 3, alpha = 0.7)

Shape 21 memungkinkan fill dan color digunakan bersama.Shape 21 supports separate fill and color.

Jalankan kode ini di RStudio untuk melihat hasil R.Run this code in RStudio to obtain the R output.

Penyesuaian grafikPlot Customization

Sesudah grafik menjawab pertanyaan dasar, pertimbangkan apakah pilihan warna, skala, label dan tema membantu pembaca memahami pola. Gunakan data mpg yang sama agar perbedaan tampilan tidak bercampur dengan perbedaan data.After a plot answers the basic question, consider whether colors, scales, labels and themes help readers understand the pattern. Use the same mpg data so appearance changes are not confounded with data changes.

Warna dan paletColor and palettes

Palet kualitatif membedakan kelompok tanpa menyatakan urutan. Palet sekuensial menunjukkan besaran numerik yang terurut; palet diverging menonjolkan penyimpangan dari referensi yang bermakna. Jangan memaksakan warna berbeda jika semua titik memiliki makna yang sama.Qualitative palettes distinguish groups without implying an order. Sequential palettes encode ordered magnitudes; diverging palettes emphasize departures from a meaningful reference. Do not force different colors when all points carry the same meaning.

Kualitatif — Set2Qualitative — Set2
Sekuensial — ViridisSequential — Viridis
Diverging — RdBuDiverging — RdBu
INTERACTIVE LAB

Color Palette ExplorerColor Palette Explorer

Pilih palet dan amati legenda diskret atau gradasi untuk nilai kontinu.Choose a palette and inspect a discrete legend or continuous gradient.

R
# Interactive R example

Untuk kategori, warna harus cukup berbeda. Untuk nilai kontinu, gradasi memudahkan pembacaan urutan. Gunakan bentuk atau label sebagai informasi redundan saat warna saja tidak cukup.For categories, colors must be distinguishable. Continuous gradients support ordering. Use shape or labels as redundant cues when color alone is insufficient.

Data mpg (234 observasi); grafik dihitung di browser, bukan output render R.mpg data (234 observations); chart computed in the browser, not rendered R output.

R
ggplot(mpg, aes(class, fill = drv)) +
  geom_bar(position = "dodge") +
  scale_fill_manual(values = c("4" = "#4C78A8",
                               "f" = "#2E8B57",
                               "r" = "#D5A74A")) +
  theme_minimal()

Gunakan scale_fill untuk geometri dengan isian. Nama warna seperti steelblue dan kode HEX sama-sama dapat digunakan.Use scale_fill for filled geometries. Named colors such as steelblue and HEX codes both work.

Jalankan kode ini di RStudio untuk melihat hasil R.Run this code in RStudio to obtain the R output.

Tema dan tampilanThemes and appearance

Theme tidak mengganti observasi atau hasil statistik. Theme mengatur panel, grid, tipografi, latar, posisi legenda, dan elemen non-data lainnya. Pilih tema yang mendukung keterbacaan, bukan tema paling ramai.A theme does not replace observations or statistical results. It controls the panel, grid, typography, background, legend position, and other non-data elements. Choose the theme that improves legibility, not the busiest one.

INTERACTIVE LAB

Theme ExplorerTheme Explorer

Ubah tema tanpa mengganti data atau posisi titik.Change the theme without changing data or point positions.

R
# Interactive R example

Perhatikan garis kisi dan latar panel. Theme_classic berguna ketika sumbu jelas dibutuhkan, theme_minimal ketika grid ringan membantu membaca nilai.Notice grid lines and panel background. theme_classic is useful for clear axes, while theme_minimal uses light grid lines to support reading.

Data mpg (234 observasi); grafik dihitung di browser, bukan output render R.mpg data (234 observations); chart computed in the browser, not rendered R output.

R
ggplot(mpg, aes(displ, hwy, color = class)) +
  geom_point(alpha = 0.7) +
  theme_minimal() +
  theme(panel.grid.minor = element_blank(),
        axis.title = element_text(face = "bold"),
        legend.position = "bottom")

theme() mengubah elemen individual; theme_set() menetapkan tema bawaan untuk grafik berikutnya, dan theme_update() memperbaruinya.theme() modifies individual elements; theme_set() sets the default for subsequent plots and theme_update() modifies it.

Jalankan kode ini di RStudio untuk melihat hasil R.Run this code in RStudio to obtain the R output.

Label, skala, dan legendaLabels, scales, and legends

Judul yang informatif menyatakan pertanyaan atau temuan, sumbu menyertakan unit, dan legenda menjelaskan arti pemetaan. Breaks menentukan tanda skala; labels menentukan teks tanda tersebut. Untuk membesarkan area tanpa menghapus data dari perhitungan statistik, gunakan coord_cartesian().An informative title states the question or finding, axes include units, and the legend explains mappings. Breaks determine tick positions; labels determine their text. Use coord_cartesian() to zoom without removing observations from statistical calculations.

INTERACTIVE LAB

Labels, Scales and LegendsLabels, Scales and Legends

Atur judul, posisi legenda, interval sumbu, dan batas zoom.Adjust the title, legend position, axis tick interval and zoom range.

R
# Interactive R example

Zoom membatasi tampilan saja; observasi tetap ada di data. Jangan hilangkan legenda jika warna belum dapat dipahami dari konteks.Zoom limits the displayed region only; the observations remain in the data. Do not remove a legend unless color is clear from context.

Data mpg (234 observasi); grafik dihitung di browser, bukan output render R.mpg data (234 observations); chart computed in the browser, not rendered R output.

R
ggplot(mpg, aes(drv, fill = drv)) +
  geom_bar() +
  scale_x_discrete(labels = c("4" = "4WD",
                              "f" = "Front", "r" = "Rear")) +
  labs(x = "Drive system", fill = "Drive system")

Label kategori mengubah teks yang ditampilkan, bukan nilai data.Category labels change displayed text, not data values.

Jalankan kode ini di RStudio untuk melihat hasil R.Run this code in RStudio to obtain the R output.

Perbandingan dan komposisiComparison and Composition

Untuk membandingkan besaran antarkategori, urutan dan panjang batang harus mudah dibaca.For category comparisons, ordering and bar length should be easy to read.

Visualisasi besaran dan perbandingan digunakan untuk membandingkan nilai antarobjek atau antarkategori.

Beberapa bentuk visualisasi yang dapat digunakan adalah diagram batang (bar chart) dan diagram lollipop (lollipop chart).

Sebagai ilustrasi, kita akan membandingkan rata-rata efisiensi bahan bakar di jalan raya ( hwy ) berdasarkan kelas kendaraan.

Pertama kita akan menghitung rata-rata hwy untuk setiap kelas kendaraan.

R
mpg_class <- mpg %>%
  group_by(class) %>%
  summarise(
    mean_hwy = mean(hwy),
    jumlah = n(),
    .groups = "drop"
  ) %>%
  arrange(mean_hwy)

Fungsi group_by() digunakan untuk mengelompokkan observasi berdasarkan class . Kemudian fungsi

summarise()  digunakan untuk menghitung rata-rata hwy  dan jumlah observasi pada masing-masing

kelas kendaraan.

Diagram Batang

Diagram batang menggunakan panjang batang untuk menunjukkan besar nilai suatu kategori.

R
ggplot(data = mpg_class,
       aes(x = reorder(class, mean_hwy),
           y = mean_hwy)) +
  geom_col() +
  coord_flip() +
  labs(
    title = "Rata-rata Efisiensi Bahan Bakar Menurut Kelas Kendaraan",
    x = NULL,
    y = "Rata-rata efisiensi bahan bakar jalan raya (mpg)"
  ) +
  theme_minimal()
R output figure

Fungsi reorder() digunakan untuk mengurutkan kelas kendaraan berdasarkan nilai mean_hwy .

Kemudian coord_flip() digunakan untuk menukar posisi sumbu sehingga nama kelas kendaraan dapat dibaca dengan lebih mudah.

Dari grafik di atas dapat terlihat kelas kendaraan yang memiliki rata-rata efisiensi bahan bakar paling tinggi maupun paling rendah.

Diagram Lollipop

Data yang sama juga dapat ditampilkan dalam bentuk diagram lollipop.

R
ggplot(data = mpg_class,
       aes(x = reorder(class, mean_hwy),
           y = mean_hwy)) +
  geom_segment(
    aes(xend = reorder(class, mean_hwy),
        y = 0,
        yend = mean_hwy)
  ) +
  geom_point(size = 3) +
  coord_flip() +
  labs(
    title = "Rata-rata Efisiensi Bahan Bakar Menurut Kelas Kendaraan",
    x = NULL,
    y = "Rata-rata efisiensi bahan bakar jalan raya (mpg)"
  ) +
  theme_minimal()
R output figure

Pada diagram lollipop, garis digunakan untuk menunjukkan besar nilai setiap kategori dan titik digunakan sebagai penanda nilai akhirnya.

Diagram batang dan diagram lollipop pada contoh di atas membawa informasi yang sama. Perbedaannya terletak pada cara informasi tersebut ditampilkan.

Magnitude and comparison visualization is used to compare values across objects or categories.

Several types of visualization that can be used include bar charts and lollipop charts.

As an illustration, we will compare the average highway fuel efficiency ( hwy ) across vehicle classes.

First, we will calculate the average hwy for each vehicle class.

R
mpg_class <- mpg %>%
  group_by(class) %>%
  summarise(
    mean_hwy = mean(hwy),
    jumlah = n(),
    .groups = "drop"
  ) %>%
  arrange(mean_hwy)
mpg_class
# A tibble: 7 × 3
  class      mean_hwy jumlah
  <chr>         <dbl>  <int>
1 pickup         16.9     33
2 suv            18.1     62
3 minivan        22.4     11
4 2seater        24.8      5
5 midsize        27.3     41
6 subcompact     28.1     35
7 compact        28.3     47

The group_by() function is used to group observations according to class . The summarise() function is then used to calculate the average hwy and the number of observations in each vehicle class.

Bar Chart

A bar chart uses the length of a bar to represent the magnitude of a value for each category.

R
ggplot(data = mpg_class,
       aes(x = reorder(class, mean_hwy),
           y = mean_hwy)) +
  geom_col() +
  coord_flip() +
  labs(
    title = "Average Highway Fuel Efficiency by Vehicle Class",
    x = NULL,
    y = "Average highway fuel efficiency (mpg)"
  ) +
  theme_minimal()
R output figure

The reorder() function is used to arrange vehicle classes according to their mean_hwy values.

Then, coord_flip() is used to switch the axes so that the names of the vehicle classes are easier to read.

From the graph above, it can be seen which vehicle classes have the highest and lowest average highway fuel efficiency.

Lollipop Chart

The same data can also be displayed using a lollipop chart.

R
ggplot(data = mpg_class,
       aes(x = reorder(class, mean_hwy),
           y = mean_hwy)) +
  geom_segment(
    aes(xend = reorder(class, mean_hwy),
        y = 0,
        yend = mean_hwy)
  ) +
  geom_point(size = 3) +
  coord_flip() +
  labs(
    title = "Average Highway Fuel Efficiency by Vehicle Class",
    x = NULL,
    y = "Average highway fuel efficiency (mpg)"
  ) +
  theme_minimal()
R output figure

In a lollipop chart, the line is used to represent the magnitude of each category, while the point marks its final value.

The bar chart and lollipop chart in the example above contain the same information. The difference lies in how the information is displayed.

Variasi diagram batangBar chart variations

geom_bar() menghitung jumlah baris per kategori secara otomatis; geom_col() menggunakan nilai y yang sudah dihitung, seperti rata-rata. Position dodge memisahkan kelompok, stack memperlihatkan total dan komposisi, fill menormalkan setiap batang menjadi proporsi 100%. Bandingkan pertanyaan yang dijawab setiap bentuk.geom_bar() counts rows by category automatically; geom_col() uses precomputed y values such as means. Position dodge separates groups, stack displays totals and composition, fill normalizes each bar to 100%. Compare the questions answered by each form.

INTERACTIVE LAB

Comparison Plot ExplorerComparison Plot Explorer

Pilih cara merangkum kendaraan dan posisi batang.Choose how to summarize vehicles and position bars.

R
# Interactive R example

Diagram jumlah mengukur banyaknya kendaraan, bukan efisiensi. Diagram rata-rata mengukur mean hwy. Batang proporsi membandingkan komposisi per kelas, bukan jumlah absolut.Count bars measure vehicle counts, not efficiency. Mean bars measure average hwy. Proportion bars compare composition within each class, not absolute counts.

Data mpg (234 observasi); grafik dihitung di browser, bukan output render R.mpg data (234 observations); chart computed in the browser, not rendered R output.

Visualisasi ProporsiVisualization of Proportion

Proporsi menjawab bagaimana keseluruhan dibagi ke dalam kategori. Pastikan penyebutnya jelas.Proportions show how a whole is divided into categories. Keep the denominator explicit.

Visualisasi proporsi digunakan untuk menunjukkan bagaimana suatu keseluruhan terbagi ke dalam beberapa kategori.

Sebagai ilustrasi, kita akan melihat proporsi kendaraan berdasarkan kelasnya.

Pertama kita akan menghitung jumlah dan proporsi setiap kelas kendaraan.

R
mpg_prop <- mpg %>%
  count(class) %>%
  mutate(
    prop = n / sum(n),
    label = scales::percent(prop, accuracy = 0.1)
  )

Fungsi count() digunakan untuk menghitung jumlah observasi pada masing-masing kelas. Kemudian proporsi diperoleh dengan membagi jumlah masing-masing kelas dengan jumlah seluruh observasi.

Diagram Batang Proporsi

Proporsi setiap kelas kendaraan dapat ditampilkan menggunakan diagram batang.

R
ggplot(data = mpg_prop,
       aes(x = reorder(class, prop),
           y = prop)) +
  geom_col() +
  coord_flip() +
  scale_y_continuous(
    labels = scales::percent_format()
  ) +
  labs(
    title = "Proporsi Kendaraan Menurut Kelas",
    x = NULL,
    y = "Proporsi"
  ) +
  theme_minimal()
R output figure

Fungsi scale_y_continuous() digunakan untuk mengubah tampilan nilai proporsi menjadi format persentase.

Diagram Donat

Data proporsi juga dapat ditampilkan dalam bentuk diagram donat (donut chart).

R
ggplot(data = mpg_prop,
       aes(x = 2,
           y = prop,
           fill = class)) +
  geom_col(
    width = 1,
    color = "white"
  ) +
  coord_polar(theta = "y") +
  xlim(0.5, 2.5) +
  labs(
    title = "Komposisi Kendaraan Menurut Kelas",
    fill = "Kelas kendaraan"
  ) +
  theme_void()
R output figure

Pada diagram di atas, setiap kelas kendaraan ditampilkan sebagai bagian dari keseluruhan lingkaran. Untuk tujuan membandingkan besar nilai secara lebih tepat, diagram batang biasanya lebih mudah dibaca karena panjang setiap batang dapat dibandingkan menggunakan skala yang sama.

Proportion visualization is used to show how a whole is divided into several categories.

As an illustration, we will examine the proportion of vehicles according to their classes.

First, we will calculate the number and proportion of observations in each vehicle class.

R
mpg_prop <- mpg %>%
  count(class) %>%
  mutate(
    prop = n / sum(n),
    label = scales::percent(prop, accuracy = 0.1)
  )

The count() function is used to calculate the number of observations in each class. The proportion is then obtained by dividing the number of observations in each class by the total number of observations.

Proportion Bar Chart

The proportion of each vehicle class can be displayed using a bar chart.

R
ggplot(data = mpg_prop,
       aes(x = reorder(class, prop),
           y = prop)) +
  geom_col() +
  coord_flip() +
  scale_y_continuous(
    labels = scales::percent_format()
  ) +
  labs(
    title = "Proportion of Vehicles by Class",
    x = NULL,
    y = "Proportion"
  ) +
  theme_minimal()
R output figure

The scale_y_continuous() function is used to display proportion values in percentage format.

Donut Chart

Proportion data can also be displayed using a donut chart.

R
ggplot(data = mpg_prop,
       aes(x = 2,
           y = prop,
           fill = class)) +
  geom_col(
    width = 1,
    color = "white"
  ) +
  coord_polar(theta = "y") +
  xlim(0.5, 2.5) +
  labs(
    title = "Composition of Vehicles by Class",
    fill = "Vehicle class"
  ) +
  theme_void()
R output figure

In the graph above, each vehicle class is displayed as a part of the entire circle.

For the purpose of comparing the magnitude of values more precisely, a bar chart is generally easier to read because the length of each bar can be compared using the same scale.

Visualisasi distribusiDistribution Visualization

Distribusi memperlihatkan variasi, bentuk, dan kemungkinan nilai ekstrem, bukan sekadar rata-rata.Distributions reveal variability, shape and potential extremes, not just averages.

Visualisasi distribusi digunakan untuk melihat bagaimana nilai suatu variabel tersebar.

Melalui visualisasi distribusi kita dapat melihat bentuk sebaran data, konsentrasi observasi, kemencengan distribusi, serta kemungkinan adanya nilai yang jauh berbeda dari observasi lainnya.

Pada bagian ini akan digunakan dataset diamonds .

Histogram

Histogram digunakan untuk melihat distribusi suatu variabel numerik.

Sebagai ilustrasi, kita akan melihat distribusi harga berlian ( price ).

R
ggplot(data = diamonds,
       aes(x = price)) +
  geom_histogram(
    bins = 35,
    color = "white"
  ) +
  labs(
    title = "Distribusi Harga Berlian",
    x = "Harga (USD)",
    y = "Frekuensi"
  ) +
  theme_minimal()
R output figure

Argumen bins digunakan untuk menentukan jumlah interval yang digunakan dalam histogram.

Dari grafik di atas dapat terlihat bahwa distribusi harga berlian tidak simetris. Sebagian besar observasi berada pada harga yang relatif rendah dan terdapat ekor distribusi yang memanjang ke arah nilai yang lebih tinggi.

Plot Kepadatan

Selain menggunakan histogram, distribusi suatu variabel juga dapat ditampilkan dalam bentuk plot kepadatan (density plot).

R
ggplot(data = diamonds,
       aes(x = price)) +
  geom_density() +
  labs(
    title = "Distribusi Harga Berlian",
    x = "Harga (USD)",
    y = "Kepadatan"
  ) +
  theme_minimal()
R output figure

Pada plot kepadatan, bentuk distribusi ditampilkan dalam bentuk kurva kontinu.

Kita juga dapat membandingkan distribusi beberapa kelompok dalam satu grafik.

Sebagai ilustrasi, distribusi harga berlian akan dibandingkan berdasarkan kualitas potongan ( cut ).

R
ggplot(data = diamonds,
       aes(x = price,
           color = cut)) +
  geom_density(linewidth = 0.8) +
  labs(
    title = "Distribusi Harga Berlian Menurut Kualitas Potongan",
    x = "Harga (USD)",
    y = "Kepadatan",
    color = "Kualitas potongan"
  ) +
  theme_minimal()
R output figure

Pada grafik di atas, setiap kategori cut ditampilkan menggunakan warna yang berbeda sehingga bentuk distribusi antar kelompok dapat dibandingkan.

Plot Violin

Untuk membandingkan distribusi variabel numerik pada beberapa kelompok, kita juga dapat menggunakan plot violin.

R
ggplot(data = diamonds,
       aes(x = cut,
           y = price,
           fill = cut)) +
  geom_violin(
    alpha = 0.7,
    show.legend = FALSE
  ) +
  labs(
    title = "Distribusi Harga Berlian Menurut Kualitas Potongan",
    x = "Kualitas potongan",
    y = "Harga (USD)"
  ) +
  theme_minimal()
R output figure

Lebar plot violin menunjukkan kepadatan observasi pada suatu rentang nilai. Bagian yang lebih lebar menunjukkan bahwa terdapat lebih banyak observasi pada rentang tersebut.

Plot violin juga dapat digabungkan dengan boxplot untuk memberikan informasi tambahan mengenai median dan kuartil.

R
ggplot(data = diamonds,
       aes(x = cut,
           y = price,
           fill = cut)) +
  geom_violin(
    alpha = 0.6,
    show.legend = FALSE
  ) +
  geom_boxplot(
    width = 0.12,
    outlier.shape = NA,
    alpha = 0.8
  ) +
  labs(
    title = "Distribusi Harga Berlian Menurut Kualitas Potongan",
    x = "Kualitas potongan",
    y = "Harga (USD)"
  ) +
  theme_minimal()
R output figure

Plot Ridgeline

Bentuk visualisasi lain yang dapat digunakan untuk membandingkan beberapa distribusi adalah plot ridgeline.

Untuk membuat plot ini digunakan package ggridges .

R
ggplot(data = diamonds,
       aes(x = price,
           y = cut,
           fill = cut)) +
  geom_density_ridges(
    alpha = 0.7,
    show.legend = FALSE
  ) +
  labs(
    title = "Distribusi Harga Berlian Berdasarkan Kualitas Potongan",
    x = "Harga (USD)",
    y = "Kualitas potongan"
  ) +
  theme_minimal()
Picking joint bandwidth of 458
R output figure

Pada plot ridgeline, masing-masing distribusi ditempatkan pada posisi yang berbeda sehingga bentuk distribusi setiap kelompok dapat dibandingkan dengan lebih mudah.

Distribution visualization is used to examine how the values of a variable are distributed.

Through distribution visualization, we can observe the shape of the data distribution, the concentration of observations, skewness, and the possible presence of values that are considerably different from the other observations.

In this section, the diamonds dataset will be used.

Histogram

A histogram is used to examine the distribution of a numerical variable.

As an illustration, we will examine the distribution of diamond prices ( price ).

R
ggplot(data = diamonds,
       aes(x = price)) +
  geom_histogram(
    bins = 35,
    color = "white"
  ) +
  labs(
    title = "Distribution of Diamond Prices",
    x = "Price (USD)",
    y = "Frequency"
  ) +
  theme_minimal()
R output figure

The bins argument is used to determine the number of intervals used in the histogram.

From the graph above, it can be seen that the distribution of diamond prices is not symmetric. Most observations are found at relatively low prices, and the distribution has a tail extending toward higher values.

Density Plot

In addition to using a histogram, the distribution of a variable can also be displayed using a density plot.

R
ggplot(data = diamonds,
       aes(x = price)) +
  geom_density() +
  labs(
    title = "Distribution of Diamond Prices",
    x = "Price (USD)",
    y = "Density"
  ) +
  theme_minimal()
R output figure

In a density plot, the shape of the distribution is displayed as a continuous curve.

We can also compare the distributions of several groups within one graph.

As an illustration, the distribution of diamond prices will be compared based on cut quality ( cut ).

R
ggplot(data = diamonds,
       aes(x = price,
           color = cut)) +
  geom_density(linewidth = 0.8) +
  labs(
    title = "Distribution of Diamond Prices by Cut Quality",
    x = "Price (USD)",
    y = "Density",
    color = "Cut quality"
  ) +
  theme_minimal()
R output figure

In the graph above, each cut category is represented using a different color so that the distributions across groups can be compared.

Violin Plot

To compare the distribution of a numerical variable across several groups, we can also use a violin plot.

R
ggplot(data = diamonds,
       aes(x = cut,
           y = price,
           fill = cut)) +
  geom_violin(
    alpha = 0.7,
    show.legend = FALSE
  ) +
  labs(
    title = "Distribution of Diamond Prices by Cut Quality",
    x = "Cut quality",
    y = "Price (USD)"
  ) +
  theme_minimal()
R output figure

The width of the violin plot represents the density of observations within a range of values. Wider sections indicate that more observations are located within that range.

A violin plot can also be combined with a boxplot to provide additional information about the median and quartiles.

R
ggplot(data = diamonds,
       aes(x = cut,
           y = price,
           fill = cut)) +
  geom_violin(
    alpha = 0.6,
    show.legend = FALSE
  ) +
  geom_boxplot(
    width = 0.12,
    outlier.shape = NA,
    alpha = 0.8
  ) +
  labs(
    title = "Distribution of Diamond Prices by Cut Quality",
    x = "Cut quality",
    y = "Price (USD)"
  ) +
  theme_minimal()
R output figure

Ridgeline Plot

Another type of visualization that can be used to compare several distributions is a ridgeline plot.

The ggridges package is used to create this plot.

R
ggplot(data = diamonds,
       aes(x = price,
           y = cut,
           fill = cut)) +
  geom_density_ridges(
    alpha = 0.7,
    show.legend = FALSE
  ) +
  labs(
    title = "Distribution of Diamond Prices by Cut Quality",
    x = "Price (USD)",
    y = "Cut quality"
  ) +
  theme_minimal()
Picking joint bandwidth of 458
R output figure

In a ridgeline plot, each distribution is placed at a different position so that the distribution pattern of each group can be compared more easily.

Lebar kelas histogramHistogram bin width

Histogram membagi data numerik ke interval, sehingga banyaknya bin atau lebarnya dapat mengubah kesan bentuk distribusi. Dataset diamonds berisi 53.940 harga, jadi tidak perlu mengambil sampel untuk histogram.A histogram partitions numeric data into intervals, so the number or width of bins can alter the apparent shape. The diamonds dataset contains 53,940 prices, so sampling is unnecessary for histograms.

INTERACTIVE LAB

Histogram ExplorerHistogram Explorer

Atur jumlah bin atau lebar interval dalam USD. Semua observasi tetap digunakan.Set the number of bins or interval width in USD. All observations are retained.

R
# Interactive R example

Bin yang terlalu lebar dapat menyembunyikan detail; bin terlalu sempit membuat distribusi tampak bergerigi. Total frekuensi harus tetap sama.Overly wide bins can hide detail; overly narrow bins can make the distribution look jagged. Total frequency must remain unchanged.

Data diamonds (53.940 observasi); frekuensi dihitung dari data penuh di browser.diamonds data (53,940 observations); counts computed from the full dataset in the browser.

Membandingkan bentuk distribusiComparing distribution shapes

Boxplot merangkum median, kuartil, whisker, dan pencilan berdasarkan aturan IQR. Violin menampilkan bentuk kepadatan; density plot membandingkan bentuk distribusi menggunakan skala kepadatan, bukan jumlah observasi. Histogram menunjukkan frekuensi pada interval tertentu.A boxplot summarizes the median, quartiles, whiskers and outliers using the IQR rule. A violin shows density shape; a density plot compares distribution shapes on a density rather than count scale. A histogram displays frequencies for intervals.

INTERACTIVE LAB

Distribution ExplorerDistribution Explorer

Bandingkan dua kualitas potongan atau seluruh kategori menggunakan beberapa bentuk ringkasan.Compare two cut qualities or all categories using different distribution summaries.

R
# Interactive R example

Gunakan boxplot untuk ringkasan posisi dan sebaran, violin atau density untuk bentuk distribusi, dan histogram untuk frekuensi. Perhatikan ukuran kelompok berbeda; bentuk kepadatan tidak mewakili banyaknya observasi.Use boxplots for location and spread, violin or density for distribution shape, and histograms for counts. Group sizes differ; density shape does not represent observation counts.

Data diamonds lengkap; kuartil dan whisker aktual, estimasi kepadatan Gaussian di Python dengan bandwidth nrd0 (pendekatan numerik, bukan hasil ggplot2).Full diamonds data; actual quartiles and whiskers, Gaussian density estimates computed in Python with nrd0 bandwidth (numerical approximation, not ggplot2 output).

Visualisasi hubunganRelationship Visualization

Diagram pencar memperlihatkan pola bersama; gunakan warna, ukuran dan garis penghalus hanya jika mendukung tujuan analisis.Scatter plots show joint patterns; use color, size and smoothing only when they support the analytical goal.

Hubungan antara dua variabel numerik dapat ditampilkan menggunakan diagram pencar.

Setiap titik pada diagram pencar menunjukkan satu observasi berdasarkan pasangan nilai pada sumbu horizontal dan vertikal.

Pada bagian ini digunakan diamonds_sample agar penumpukan titik pada grafik dapat dikurangi.

Diagram Pencar

Sebagai ilustrasi, kita akan melihat hubungan antara berat berlian ( carat ) dan harga berlian ( price ).

R
ggplot(data = diamonds_sample,
       aes(x = carat,
           y = price)) +
  geom_point(alpha = 0.5) +
  labs(
    title = "Hubungan Berat dan Harga Berlian",
    x = "Berat berlian (carat)",
    y = "Harga (USD)"
  ) +
  theme_minimal()
R output figure

Argumen alpha digunakan untuk mengatur transparansi titik. Pengaturan transparansi dapat membantu ketika terdapat beberapa titik yang saling bertumpuk.

Dari grafik di atas terlihat bahwa harga berlian cenderung meningkat ketika berat berlian bertambah.

Garis Penghalus

Untuk membantu melihat pola umum hubungan antara dua variabel, kita dapat menambahkan garis penghalus (smoothing line) menggunakan geom_smooth() .

R
ggplot(data = diamonds_sample,
       aes(x = carat,
           y = price)) +
  geom_point(alpha = 0.35) +
  geom_smooth(
    se = FALSE,
    linewidth = 1
  ) +
  labs(
    title = "Pola Hubungan Berat dan Harga Berlian",
    x = "Berat berlian (carat)",
    y = "Harga (USD)"
  ) +
  theme_minimal()
`geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'
R output figure

Fungsi geom_smooth() menambahkan garis yang membantu memperlihatkan kecenderungan umum hubungan antara kedua variabel.

Menambahkan Informasi Kategori

Informasi lain dapat ditambahkan pada diagram pencar menggunakan elemen visual.

Sebagai ilustrasi, variabel cut akan ditampilkan menggunakan warna.

R
ggplot(data = diamonds_sample,
       aes(x = carat,
           y = price,
           color = cut)) +
  geom_point(alpha = 0.5) +
  labs(
    title = "Hubungan Berat dan Harga Berlian Berdasarkan Kualitas Potongan",
    x = "Berat berlian (carat)",
    y = "Harga (USD)",
    color = "Kualitas potongan"
  ) +
  theme_minimal()
R output figure

Sekarang grafik menampilkan tiga informasi, yaitu berat berlian, harga berlian, dan kualitas potongannya.

Diagram Gelembung

Ukuran titik juga dapat digunakan untuk menampilkan variabel tambahan. Bentuk visualisasi ini sering disebut sebagai diagram gelembung (bubble chart).

Sebagai ilustrasi digunakan kembali data mpg .

R
ggplot(data = mpg,
       aes(x = displ,
           y = hwy,
           size = cyl,
           color = drv)) +
  geom_point(alpha = 0.65) +
  labs(
    title = "Kapasitas Mesin dan Efisiensi Bahan Bakar",
    x = "Kapasitas mesin (liter)",
    y = "Efisiensi bahan bakar jalan raya (mpg)",
    size = "Jumlah silinder",
    color = "Sistem penggerak"
  ) +
  theme_minimal()
R output figure

Pada grafik di atas, posisi menunjukkan kapasitas mesin dan efisiensi bahan bakar, ukuran menunjukkan jumlah silinder, sedangkan warna menunjukkan jenis sistem penggerak kendaraan.

Matriks Diagram Pencar

Jika terdapat beberapa variabel numerik yang ingin diamati secara bersamaan, package GGally menyediakan fungsi ggpairs() .

Sebagai ilustrasi digunakan beberapa variabel dari diamonds_sample .

R
diamonds_sample %>%
  select(carat, depth, table, price) %>%
  ggpairs()
R output figure

Grafik di atas menampilkan distribusi masing-masing variabel serta hubungan antar pasangan variabel.

Semakin banyak variabel yang dimasukkan, semakin kompleks visualisasi yang dihasilkan. Oleh karena itu, variabel yang digunakan sebaiknya tetap disesuaikan dengan kebutuhan analisis.

The relationship between two numerical variables can be displayed using a scatter plot.

Each point in a scatter plot represents one observation based on a pair of values on the horizontal and vertical axes.

In this section, diamonds_sample is used to reduce point overlap in the graph.

Scatter Plot

As an illustration, we will examine the relationship between diamond weight ( carat ) and diamond price ( price ).

R
ggplot(data = diamonds_sample,
       aes(x = carat,
           y = price)) +
  geom_point(alpha = 0.5) +
  labs(
    title = "Relationship Between Diamond Weight and Price",
    x = "Diamond weight (carat)",
    y = "Price (USD)"
  ) +
  theme_minimal()
R output figure

The alpha argument is used to control point transparency. Transparency can help when several points overlap.

From the graph above, it can be seen that diamond prices tend to increase as diamond weight increases.

Smoothing Line

To help identify the general pattern of the relationship between two variables, a smoothing line can be added using geom_smooth() .

R
ggplot(data = diamonds_sample,
       aes(x = carat,
           y = price)) +
  geom_point(alpha = 0.35) +
  geom_smooth(
    se = FALSE,
    linewidth = 1
  ) +
  labs(
    title = "Relationship Pattern Between Diamond Weight and Price",
    x = "Diamond weight (carat)",
    y = "Price (USD)"
  ) +
  theme_minimal()
`geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'
R output figure

The geom_smooth() function adds a line that helps show the general trend of the relationship between the two variables.

Adding Categorical Information

Additional information can be added to a scatter plot using visual elements.

As an illustration, the cut variable will be represented using color.

R
ggplot(data = diamonds_sample,
       aes(x = carat,
           y = price,
           color = cut)) +
  geom_point(alpha = 0.5) +
  labs(
    title = "Relationship Between Diamond Weight and Price by Cut Quality",
    x = "Diamond weight (carat)",
    y = "Price (USD)",
    color = "Cut quality"
  ) +
  theme_minimal()
R output figure

The graph now displays three types of information: diamond weight, diamond price, and cut quality.

Bubble Chart

Point size can also be used to display an additional variable. This type of visualization is often referred to as a bubble chart.

As an illustration, the mpg dataset is used again.

R
ggplot(data = mpg,
       aes(x = displ,
           y = hwy,
           size = cyl,
           color = drv)) +
  geom_point(alpha = 0.65) +
  labs(
    title = "Engine Displacement and Fuel Efficiency",
    x = "Engine displacement (liters)",
    y = "Highway fuel efficiency (mpg)",
    size = "Number of cylinders",
    color = "Drive system"
  ) +
  theme_minimal()
R output figure

In the graph above, position represents engine displacement and fuel efficiency, size represents the number of cylinders, while color represents the vehicle drive system.

Scatterplot Matrix

If several numerical variables need to be examined simultaneously, the GGally package provides the

ggpairs()  function.

As an illustration, several variables from diamonds_sample are used.

R
diamonds_sample %>%
  select(carat, depth, table, price) %>%
  ggpairs()
R output figure

The graph above displays the distribution of each variable as well as the relationships between pairs of variables.

The more variables included, the more complex the visualization becomes. Therefore, the variables used should still be selected according to the needs of the analysis.

Pengembangan diagram pencarExtending scatter plots

Gunakan diamonds_sample untuk mengeksplorasi carat dan price, dengan cut sebagai warna dan depth sebagai ukuran apabila diperlukan. Bubble chart dengan cyl dan drv harus menggunakan mpg karena kedua variabel itu tidak terdapat pada diamonds. Tambahkan pemetaan hanya jika relevan; terlalu banyak estetika sekaligus dapat membingungkan.Use diamonds_sample to explore carat and price, with cut as color and depth as size when appropriate. A bubble chart using cyl and drv must use mpg because those variables do not occur in diamonds. Add mappings only when relevant; too many aesthetics can confuse readers.

R
ggplot(diamonds_sample, aes(carat, price, color = cut, size = depth)) +
  geom_point(alpha = 0.3) +
  scale_size_continuous(range = c(1, 4)) +
  theme_minimal()

Ukuran titik menunjukkan depth, warna menunjukkan cut. Perhatikan overlap; jangan menginterpretasikan korelasi sebagai hubungan sebab-akibat.Size represents depth, color represents cut. Watch overlap; do not interpret correlation as causation.

Jalankan kode ini di RStudio untuk melihat hasil R.Run this code in RStudio to obtain the R output.

Membandingkan kelompok dengan facetComparing Groups with Facets

Ketika terlalu banyak kelompok bertumpuk di satu grafik, pisahkan panel berdasarkan kategori. facet_wrap() membuat susunan panel dari satu atau beberapa variabel, sedangkan facet_grid() membuat matriks berdasarkan baris dan kolom. Gunakan fixed scales untuk membandingkan besaran antar panel; free scales memperjelas pola internal tetapi membuat perbandingan besaran lebih sulit.When many groups overlap in one plot, separate panels by category. facet_wrap() lays out panels from one or more variables, while facet_grid() creates a row-by-column matrix. Use fixed scales to compare magnitudes across panels; free scales reveal within-panel patterns but make comparisons of magnitude harder.

INTERACTIVE LAB

Facet ExplorerFacet Explorer

Pilih variabel pengelompokan, jumlah kolom dan skala.Choose the grouping variable, number of columns and scales.

R
# Interactive R example

Dengan skala tetap, perbedaan rentang hwy dapat dibandingkan langsung. Dengan skala bebas, lihat label sumbu setiap panel sebelum menyimpulkan perbedaan kemiringan.With fixed scales, hwy ranges can be compared directly. With free scales, inspect each panel’s axis labels before inferring slope differences.

Data mpg (234 observasi); grafik dihitung di browser, bukan output render R.mpg data (234 observations); chart computed in the browser, not rendered R output.

Deret waktu dan trenTime Series and Trend

Untuk data deret waktu, pertahankan urutan tanggal agar perubahan dan tren dapat terlihat.For time series, retain chronological order so changes and trends remain visible.

Data deret waktu merupakan data yang mempunyai urutan berdasarkan waktu.

Untuk melihat perubahan nilai dari waktu ke waktu, bentuk visualisasi yang umum digunakan adalah diagram garis dan diagram area.

Pada bagian ini digunakan dataset economics .

R
economics %>%
  select(date, unemploy, psavert) %>%
  head()
# A tibble: 6 × 3
  date       unemploy psavert
  <date>        <dbl>   <dbl>
1 1967-07-01     2944    12.6
2 1967-08-01     2945    12.6
3 1967-09-01     2958    11.9
4 1967-10-01     3143    12.9
5 1967-11-01     3066    12.8
6 1967-12-01     3018    11.8

Diagram Garis

Sebagai ilustrasi, kita akan melihat perkembangan jumlah pengangguran ( unemploy ) dari waktu ke waktu.

R
ggplot(data = economics,
       aes(x = date,
           y = unemploy)) +
  geom_line(linewidth = 0.7) +
  scale_y_continuous(
    labels = scales::comma
  ) +
  labs(
    title = "Perkembangan Jumlah Pengangguran",
    x = "Waktu",
    y = "Jumlah pengangguran"
  ) +
  theme_minimal()
R output figure

Pada diagram garis, observasi dihubungkan berdasarkan urutan waktu sehingga perubahan nilai dapat diamati dari satu periode ke periode berikutnya.

Diagram Area

Data yang sama juga dapat ditampilkan dalam bentuk diagram area.

R
ggplot(data = economics,
       aes(x = date,
           y = unemploy)) +
  geom_area(alpha = 0.6) +
  scale_y_continuous(
    labels = scales::comma
  ) +
  labs(
    title = "Perkembangan Jumlah Pengangguran",
    x = "Waktu",
    y = "Jumlah pengangguran"
  ) +
  theme_minimal()
R output figure

Pada diagram area, bagian di bawah garis diberikan warna sehingga besar nilai juga ditunjukkan melalui luas area.

Diagram garis lebih menekankan pola perubahan dari waktu ke waktu, sedangkan diagram area memberikan penekanan yang lebih besar pada besarnya nilai.

Time series data consist of observations ordered according to time.

To examine changes in values over time, commonly used visualizations include line charts and area charts.

In this section, the economics dataset is used.

R
economics %>%
  select(date, unemploy, psavert) %>%
  head()
# A tibble: 6 × 3
  date       unemploy psavert
  <date>        <dbl>   <dbl>
1 1967-07-01     2944    12.6
2 1967-08-01     2945    12.6
3 1967-09-01     2958    11.9
4 1967-10-01     3143    12.9
5 1967-11-01     3066    12.8
6 1967-12-01     3018    11.8

Line Chart

As an illustration, we will examine changes in the number of unemployed people ( unemploy ) over time.

R
ggplot(data = economics,
       aes(x = date,
           y = unemploy)) +
  geom_line(linewidth = 0.7) +
  scale_y_continuous(
    labels = scales::comma
  ) +
  labs(
    title = "Changes in the Number of Unemployed People",
    x = "Time",
    y = "Number of unemployed people"
  ) +
  theme_minimal()
R output figure

In a line chart, observations are connected according to their time order so that changes in values can be observed from one period to another.

Area Chart

The same data can also be displayed using an area chart.

R
ggplot(data = economics,
       aes(x = date,
           y = unemploy)) +
  geom_area(alpha = 0.6) +
  scale_y_continuous(
    labels = scales::comma
  ) +
  labs(
    title = "Changes in the Number of Unemployed People",
    x = "Time",
    y = "Number of unemployed people"
  ) +
  theme_minimal()
R output figure

In an area chart, the area below the line is filled so that the magnitude of the values is also represented by the size of the area.

A line chart places greater emphasis on patterns of change over time, while an area chart gives greater emphasis to the magnitude of the values.

Tren, titik observasi, dan konteks waktuTrends, observations, and temporal context

Titik di atas garis membantu menandai waktu pengamatan. Untuk deret waktu dengan frekuensi rapat, titik yang terlalu besar mengurangi keterbacaan. Pada grafik unemploy, gunakan ribuan orang sebagai satuan: garis referensi 8.000 berarti delapan juta orang, bukan delapan orang. Nilai ini hanya contoh ambang, bukan standar kebijakan.Points on a line help identify observation dates. For densely sampled time series, overly large points reduce legibility. In the unemploy series, units are thousands of people: a reference line at 8,000 means eight million people, not eight people. This is an illustrative threshold, not a policy standard.

R
ggplot(economics, aes(date, unemploy)) +
  geom_line(linewidth = 0.7, color = "steelblue") +
  geom_point(size = 0.6, alpha = 0.5) +
  labs(x = "Date", y = "Unemployed (thousands)") +
  theme_minimal()

Garis menunjukkan urutan waktu, titik menunjukkan setiap pengamatan.The line shows temporal order; points indicate observations.

Jalankan kode ini di RStudio untuk melihat hasil R.Run this code in RStudio to obtain the R output.

Menambahkan konteks dan anotasiAdding Context and Annotations

Grafik dapat menyoroti nilai penting, wilayah, atau observasi melalui garis referensi dan anotasi. Gunakan geom_hline(), geom_vline(), geom_abline() atau annotate(). Untuk label observasi yang saling bertumpuk, ggrepel memindahkan teks tanpa memindahkan titik. Garis diagonal harus memiliki arti dalam satuan kedua sumbu; bukan dekorasi.Plots can highlight important values, regions or observations with reference lines and annotations. Use geom_hline(), geom_vline(), geom_abline() or annotate(). For overlapping observation labels, ggrepel moves text without moving points. A diagonal line must have meaning in both axis units, not merely decoration.

INTERACTIVE LAB

Annotation ExplorerAnnotation Explorer

Atur batas kapasitas mesin dan efisiensi; tandai observasi yang berada pada wilayah kapasitas besar dan MPG rendah.Set engine-size and efficiency thresholds; highlight observations with large engines and low MPG.

R
# Interactive R example

Wilayah berarsir adalah definisi eksploratif, bukan hasil klasifikasi model. Garis acuan tidak berarti sebab-akibat; label hanya memperjelas observasi terpilih.The shaded region is an exploratory definition, not a model classification result. Reference lines do not imply causation; labels clarify selected observations.

Data mpg (234 observasi); grafik dihitung di browser, bukan output render R.mpg data (234 observations); chart computed in the browser, not rendered R output.

R
ggplot(mpg, aes(cty, hwy)) +
  geom_point(alpha = 0.7) +
  geom_abline(intercept = 0, slope = 1, linetype = "dashed") +
  coord_equal() + theme_minimal()

Kedua sumbu memiliki satuan MPG. Garis y = x menunjukkan efisiensi kota dan jalan raya yang sama.Both axes are measured in MPG. The y = x line indicates equal city and highway efficiency.

Jalankan kode ini di RStudio untuk melihat hasil R.Run this code in RStudio to obtain the R output.

Visualisasi geospasialGeospatial Visualization

Peta memadukan geometri wilayah dengan nilai atribut. Pastikan kunci penggabungan sesuai sebelum memberi warna.Maps combine geographic geometry with attributes. Verify join keys before assigning colors.

Visualisasi geospasial digunakan untuk menampilkan informasi yang berkaitan dengan lokasi geografis.

Salah satu bentuk visualisasi geospasial adalah peta tematik, yaitu peta yang menggunakan elemen visual seperti warna untuk menunjukkan variasi nilai suatu variabel berdasarkan wilayah.

Pada ilustrasi kali ini digunakan data negara bagian Amerika Serikat.

Fungsi map_data() membutuhkan package maps . Apabila package tersebut belum tersedia, package dapat diinstal melalui Console menggunakan sintaks berikut.

R
install.packages("maps")

Menyiapkan Data

Dataset state.x77 merupakan dataset bawaan R yang berisi beberapa informasi mengenai negara bagian di Amerika Serikat.

Pertama, dataset tersebut diubah menjadi data.frame .

R
state_data <- as.data.frame(state.x77) %>%
  rownames_to_column("region") %>%
  mutate(region = tolower(region))

Nama negara bagian diubah menjadi huruf kecil menggunakan tolower() agar formatnya sama dengan nama wilayah pada data peta.

Kemudian kita akan mengambil data koordinat peta negara bagian Amerika Serikat.

R
us_map <- map_data("state")

Data tersebut memiliki variabel long dan lat yang menunjukkan koordinat pembentuk setiap wilayah. Selanjutnya, data peta digabungkan dengan state_data menggunakan variabel region .

R
us_map_data <- us_map %>%
  left_join(state_data,
            by = "region")

Setelah proses penggabungan dilakukan, nilai pada state.x77 dapat ditampilkan berdasarkan wilayah geografis.

Peta Tematik

Sebagai ilustrasi, kita akan menampilkan variabel Income .

R
ggplot(data = us_map_data,
       aes(x = long,
           y = lat,
           group = group,
           fill = Income)) +
  geom_polygon(
    color = "white",
    linewidth = 0.15
  ) +
  coord_fixed(1.3) +
  scale_fill_viridis_c(
    labels = scales::comma
  ) +
  labs(
    title = "Peta Tematik Pendapatan per Negara Bagian",
    fill = "Pendapatan"
  ) +
  theme_void()
R output figure

Pada grafik di atas, posisi dan bentuk poligon menunjukkan wilayah geografis. Sementara itu, warna menunjukkan nilai Income .

Karena Income berupa variabel numerik, warna ditampilkan dalam bentuk gradasi untuk menunjukkan perbedaan nilai antarwilayah.

Geospatial visualization is used to display information related to geographic locations. One type of geospatial visualization is a thematic map, which uses visual elements such as color to represent variation in a variable across geographic regions.

In this illustration, data from the states of the United States are used.

The map_data() function requires the maps package. If the package is not yet available, it can be installed through the Console using the following syntax.

R
install.packages("maps")

Preparing the Data

The state.x77 dataset is a built-in R dataset containing several characteristics of states in the United States.

First, the dataset is converted into a data.frame .

R
state_data <- as.data.frame(state.x77) %>%
  rownames_to_column("region") %>%
  mutate(region = tolower(region))

State names are converted to lowercase using tolower() so that their format matches the region names in the map data.

Next, we will obtain the coordinate data for the state boundaries of the United States.

R
us_map <- map_data("state")

The data contain the variables long and lat , which represent the coordinates that form each geographic region. The map data are then combined with state_data using the region variable.

R
us_map_data <- us_map %>%
  left_join(state_data,
            by = "region")

After the merging process is completed, the values from state.x77 can be displayed according to geographic region.

Thematic Map

As an illustration, we will display the Income variable.

R
ggplot(data = us_map_data,
       aes(x = long,
           y = lat,
           group = group,
           fill = Income)) +
  geom_polygon(
    color = "white",
    linewidth = 0.15
  ) +
  coord_fixed(1.3) +
  scale_fill_viridis_c(
    labels = scales::comma
  ) +
  labs(
    title = "Thematic Map of Income by State",
    fill = "Income"
  ) +
  theme_void()
R output figure

In the graph above, the position and shape of the polygons represent geographic regions. Meanwhile, color represents the value of Income .

Because Income is a numerical variable, color is displayed as a gradient to represent differences in values across regions.

Visualisasi interaktifInteractive Visualization

Grafik interaktif memperluas eksplorasi melalui hover. Jalankan ggplotly di RStudio untuk mengaktifkan widget.Interactive plots support exploration through hover. Run ggplotly in RStudio to activate the widget.

Selain visualisasi statis, suatu grafik juga dapat dibuat menjadi interaktif.

Visualisasi interaktif memungkinkan pengguna memperoleh informasi tambahan melalui interaksi dengan grafik, misalnya dengan mengarahkan kursor pada suatu titik.

Package plotly dapat digunakan untuk mengubah grafik yang dibuat menggunakan ggplot2 menjadi grafik interaktif.

Pertama, kita akan membuat diagram pencar dan menyimpannya dalam objek p .

R
p <- ggplot(data = diamonds_sample,
            aes(x = carat,
                y = price,
                color = cut)) +
  geom_point(alpha = 0.6) +
  labs(
    title = "Hubungan Berat dan Harga Berlian",
    x = "Berat berlian (carat)",
    y = "Harga (USD)",
    color = "Kualitas potongan"
  ) +
  theme_minimal()

Kemudian objek p dapat diubah menjadi visualisasi interaktif menggunakan fungsi berikut.

R
ggplotly(p)

Fungsi ggplotly() dapat dijalankan melalui Console atau digunakan pada dokumen dengan output HTML. Pada output PDF, grafik interaktif tidak dapat ditampilkan secara langsung.

In addition to static visualization, a graph can also be made interactive.

Interactive visualization allows users to obtain additional information by interacting with the graph, for example by moving the cursor over a particular point.

The plotly package can be used to convert a graph created using ggplot2 into an interactive graph.

First, we will create a scatter plot and store it in an object called p .

R
p <- ggplot(data = diamonds_sample,
            aes(x = carat,
                y = price,
                color = cut)) +
  geom_point(alpha = 0.6) +
  labs(
    title = "Relationship Between Diamond Weight and Price",
    x = "Diamond weight (carat)",
    y = "Price (USD)",
    color = "Cut quality"
  ) +
  theme_minimal()

The p object can then be converted into an interactive visualization using the following function.

R
ggplotly(p)

The ggplotly() function can be executed through the Console or used in a document with HTML output. Interactive graphs cannot be displayed directly in PDF output.

Visualisasi data yang efektifEffective Data Visualization

Skala sumbu dan warna dapat mengubah persepsi. Bandingkan representasi dengan hati-hati.Axis scales and colors can change perception. Compare representations carefully.

Selain memilih bentuk grafik yang sesuai, tampilan grafik juga perlu diperhatikan agar informasi dapat diterima dengan jelas oleh pembaca.

Beberapa hal yang perlu diperhatikan antara lain penggunaan skala, warna, label, jumlah informasi yang ditampilkan, serta pemilihan elemen visual yang sesuai.

Pengaruh Skala Sumbu

Skala sumbu dapat memengaruhi cara pembaca melihat perbedaan nilai pada suatu grafik. Sebagai ilustrasi, digunakan data sederhana berikut.

R
survey <- tibble(
  category = c("A", "B", "C"),
  score = c(79, 82, 85)
)

Kemudian dibuat grafik dengan rentang sumbu yang relatif sempit.

R
plot_1 <- ggplot(data = survey,
                 aes(x = category,
                     y = score)) +
  geom_col() +
  coord_cartesian(
    ylim = c(75, 86)
  ) +
  labs(
    title = "Skala Sumbu Dipersempit",
    x = "Kategori",
    y = "Skor"
  ) +
  theme_minimal()

Selanjutnya dibuat grafik kedua menggunakan skala 0 sampai 100.

R
plot_2 <- ggplot(data = survey,
                 aes(x = category,
                     y = score)) +
  geom_col() +
  scale_y_continuous(
    limits = c(0, 100)
  ) +
  labs(
    title = "Skala Skor 0-100",
    x = "Kategori",
    y = "Skor"
  ) +
  theme_minimal()

Kedua grafik dapat ditampilkan secara berdampingan menggunakan fungsi ggarrange() .

R
ggpubr::ggarrange(
  plot_1,
  plot_2,
  ncol = 2
)
R output figure

Kedua grafik menggunakan nilai yang sama, tetapi dapat memberikan kesan visual yang berbeda.

Pada grafik pertama, perbedaan antar kategori terlihat lebih besar karena rentang sumbu dipersempit. Pada diagram batang, panjang batang merupakan elemen utama dalam membandingkan nilai. Oleh karena itu, pemilihan skala sumbu perlu diperhatikan agar tidak memberikan kesan yang keliru.

Penggunaan Warna

Warna dapat digunakan untuk membantu pembaca membedakan kelompok atau melihat perubahan nilai.

Sebagai ilustrasi, kita akan menggunakan warna untuk membedakan sistem penggerak kendaraan.

R
ggplot(data = mpg,
       aes(x = displ,
           y = hwy,
           color = drv)) +
  geom_point(size = 2.5) +
  labs(
    title = "Sistem Penggerak Kendaraan",
    x = "Kapasitas mesin (liter)",
    y = "Efisiensi bahan bakar jalan raya (mpg)",
    color = "Sistem penggerak"
  ) +
  theme_minimal()
R output figure

Pada grafik tersebut, warna digunakan untuk membedakan kategori pada variabel drv .

Sementara itu, pada variabel numerik warna dapat digunakan dalam bentuk gradasi seperti yang digunakan pada peta tematik sebelumnya.

Warna sebaiknya digunakan untuk membantu menyampaikan informasi dan bukan hanya sebagai hiasan.

In addition to selecting an appropriate type of graph, the appearance of the graph also needs to be considered so that the information can be clearly understood by the reader.

Several aspects need to be considered, including the use of scales, colors, labels, the amount of information displayed, and the selection of appropriate visual elements.

Effect of Axis Scale

Axis scales can influence how readers perceive differences in values within a graph.

As an illustration, the following simple dataset is used.

R
survey <- tibble(
  category = c("A", "B", "C"),
  score = c(79, 82, 85)
)

A graph is then created using a relatively narrow axis range.

R
plot_1 <- ggplot(data = survey,
                 aes(x = category,
                     y = score)) +
  geom_col() +
  coord_cartesian(
    ylim = c(75, 86)
  ) +
  labs(
    title = "Narrowed Axis Scale",
    x = "Category",
    y = "Score"
  ) +
  theme_minimal()

Next, a second graph is created using a scale ranging from 0 to 100.

R
plot_2 <- ggplot(data = survey,
                 aes(x = category,
                     y = score)) +
  geom_col() +
  scale_y_continuous(
    limits = c(0, 100)
  ) +
  labs(
    title = "Score Scale from 0 to 100",
    x = "Category",
    y = "Score"
  ) +
  theme_minimal()

The two graphs can be displayed side by side using the ggarrange() function.

R
ggpubr::ggarrange(
  plot_1,
  plot_2,
  ncol = 2
)
R output figure

Both graphs use the same values but may give different visual impressions.

In the first graph, the differences between categories appear larger because the axis range is narrowed. In a bar chart, bar length is the main visual element used to compare values. Therefore, the choice of axis scale needs to be considered carefully so that it does not create a misleading impression.

Use of Color

Color can be used to help readers distinguish groups or identify changes in values.

As an illustration, we will use color to distinguish vehicle drive systems.

R
ggplot(data = mpg,
       aes(x = displ,
           y = hwy,
           color = drv)) +
  geom_point(size = 2.5) +
  labs(
    title = "Vehicle Drive Systems",
    x = "Engine displacement (liters)",
    y = "Highway fuel efficiency (mpg)",
    color = "Drive system"
  ) +
  theme_minimal()
R output figure

In the graph above, color is used to distinguish categories in the drv variable.

For numerical variables, color can instead be represented using a gradient, as used previously in the thematic map.

Color should be used to help communicate information rather than simply as decoration.

Skala sumbu dan persepsiAxis scale and perception

INTERACTIVE LAB

Axis Scale ExplorerAxis Scale Explorer

Bandingkan nilai contoh 80 dan 90 ketika awal sumbu berubah.Compare the example values 80 and 90 when the axis origin changes.

R
# Interactive R example

Panjang batang harus dibandingkan terhadap baseline yang sama. Untuk bar chart, awal nol biasanya tepat. Zoom yang memotong batang dapat menyesatkan meskipun selisih nilai tetap 10.Bar lengths must be compared against a common baseline. A zero baseline is usually appropriate for bar charts. Cropping bars can mislead even though the difference remains 10.

Data ilustratif 80 dan 90; bukan hasil pemodelan.Illustrative values 80 and 90; not model results.

Memilih grafik sesuai pertanyaanChoosing an appropriate plot

Mulailah dari tujuan, bukan pilihan geom. Gunakan bar atau lollipop untuk membandingkan kategori; histogram dan density untuk distribusi satu numerik; boxplot, violin dan ridgeline untuk distribusi antarkelompok; scatter dan bubble untuk hubungan; line atau area untuk tren; diagram proporsi atau donat untuk komposisi; peta tematik untuk pola spasial. Gunakan scatterplot matrix jika ingin membandingkan banyak pasangan numerik.Start with the objective, not the geom. Use bars or lollipops for categories; histograms and density plots for one numeric distribution; boxplots, violins and ridgelines for grouped distributions; scatter and bubble plots for relationships; line or area charts for trends; proportion bars or donuts for composition; thematic maps for spatial patterns. Use a scatterplot matrix to inspect several numeric pairs.

Grafik yang baik memungkinkan pembaca memahami data, unit, penyebut, dan kelompok tanpa menebak. Periksa bahwa skala dan warna tidak menyamarkan pola; gunakan anotasi secukupnya.A good chart allows readers to understand data, units, denominators and groups without guessing. Ensure scales and color do not obscure patterns; use annotations sparingly.

Menyimpan dan mengekspor grafikSaving and Exporting Plots

Simpan grafik sebagai objek R sebelum mengekspor agar tidak bergantung pada grafik terakhir di panel Plots. ggsave() menentukan format berdasarkan ekstensi file, serta dapat mengatur ukuran fisik, DPI untuk format raster, dan warna latar. PDF/SVG merupakan format vektor; PNG merupakan raster. Transparansi berguna untuk slide tetapi dapat mengurangi keterbacaan pada latar tertentu.Store a plot as an R object before exporting so the result does not depend on the last plot in the Plots pane. ggsave() infers format from the file extension and can control physical dimensions, raster DPI, and background. PDF/SVG are vector formats; PNG is raster. Transparency can help with slides but may reduce legibility on some backgrounds.

INTERACTIVE LAB

Export ConfigurationExport Configuration

Tentukan format, ukuran, resolusi, dan latar; salin sintaks yang sesuai ke RStudio.Choose format, size, resolution and background; copy the generated code into RStudio.

R
# Interactive R example

Hasil file disimpan pada working directory R jika tidak memberi path lengkap. Gunakan getwd() untuk menemukannya. DPI mengatur jumlah piksel pada PNG, bukan resolusi intrinsik format vektor.The file is saved in the R working directory if no full path is given. Use getwd() to locate it. DPI controls PNG pixel dimensions, not the intrinsic resolution of vector formats.

Konfigurasi ekspor; file grafik dibuat ketika ggsave() dijalankan di RStudio.Export configuration; the plot file is created when ggsave() runs in RStudio.

Latihan mandiriIndependent Exercise

Terapkan alur yang sama pada lima pertanyaan berikut: rumuskan tujuan, siapkan data, pilih geom dan pemetaan, sesuaikan tampilan, lalu tulis interpretasi berbasis grafik. Kerjakan secara mandiri; tidak ada jawaban numerik yang diberikan.Apply the same workflow to the five tasks below: formulate the goal, prepare the data, choose geoms and mappings, customize the plot, and write a plot-based interpretation. Work independently; no numerical answers are provided.

1. Perbandingan — mpg1. Comparison — mpg

Hitung rata-rata cty untuk setiap manufacturer, pilih 10 tertinggi, buat grafik perbandingan dan ringkas temuan utama.Calculate average cty for each manufacturer, select the top 10, create a comparison plot, and summarize the main finding.

2. Distribusi — diamonds2. Distribution — diamonds

Pilih satu variabel numerik, bandingkan distribusinya berdasarkan satu variabel kategorik, perbaiki tampilan grafik dan interpretasikan pola.Choose one numerical variable, compare its distribution across one categorical variable, improve the plot appearance, and explain the pattern.

3. Hubungan — diamonds_sample3. Relationship — diamonds_sample

Visualisasikan carat dan price, tambahkan minimal satu aesthetic relevan, lakukan penyesuaian dan jelaskan hubungan.Visualize carat and price, add at least one relevant aesthetic, apply suitable customization, and explain the relationship.

4. Deret waktu — economics4. Time series — economics

Visualisasikan psavert terhadap waktu; gunakan label dan tema yang sesuai, tandai perubahan penting dengan anotasi, lalu berikan interpretasi singkat.Visualize psavert over time, use clear labels and a suitable theme, annotate a noticeable change, and provide a short interpretation.

5. Redesign visualisasi5. Improve a visualization

Buat satu grafik dengan minimal tiga masalah penyajian, kemudian redesign menggunakan warna, tema, skala, label, legenda atau anotasi yang sesuai. Jelaskan tiga perbaikannya.Create a visualization with at least three presentation problems, redesign using appropriate color, theme, scale, labels, legend or annotations, and explain the three improvements.

Pengumpulan: publikasikan seluruh jawaban dalam satu dokumen R Markdown di RPubs. Serahkan tautan RPubs sesuai instruksi pengajar.Submission: publish all answers in one R Markdown document on RPubs. Submit the RPubs link according to the instructor’s directions.

Ringkasan dan dokumentasiSummary and Documentation

Visualisasi yang efektif dimulai dari pertanyaan analitik dan tipe variabel. Gunakan data, aesthetics, geometry, labels, dan theme secara sadar. Bandingkan pilihan representasi tanpa mengubah data; perhatikan unit, penyebut, skala, overlap, dan konteks. Simpan grafik sesuai tujuan penggunaan dan jelaskan temuan menggunakan bahasa yang tidak melampaui bukti.Effective visualization starts with an analytical question and variable types. Use data, aesthetics, geometry, labels, and theme deliberately. Compare representations without changing data; pay attention to units, denominators, scales, overlap, and context. Export charts for their intended use and explain findings without exceeding the evidence.

Dokumentasi pendukungSupporting documentation

ggplot2 · dplyr · ggrepel · R Charts · ggridges · plotly

PENULISAUTHOR
Unique Desyrre A. Resiloy