Algoritma & Struktur Data
~ Visualisasi Data ~
| Kontak | : \(\downarrow\) |
| ferdinand.widjaya@student.matanauniversity.ac.id | |
| https://www.instagram.com/fe_nw/ | |
| RPubs | https://rpubs.com/ferdnw/ |
Visualisasi Data Visualisasi data merupakan suatu teknik mengubah informasi atau data yang ada menjadi bentuk visual yang lebih mudah untuk dilihat atau diproses seperti grafik atau chart. Dalam mempresentasikan data, akan lebih menarik untuk melihat visualized data daripada raw data. R merupakan salah satu software yang capable dalam melakukan hal tersebut.
Univariat (Single Variabel)
Visualisasi data dari satu variabel saja, bisa dalam bentuk Kategoris(Bukan angka, tidak dapat dihitung contohnya jenis kelamin, asal daerah) dan Numerik (Berupa Angka, dapat dihitung, seperti Umur, Salary)
Variabel Kategori
Variabel Non-Angka biasanya dipresentasikan dalam bentuk Bar Chart, Pie Chart, dan Pohon. Contoh visualisasi Data Marriage by dibawah
Bar Chart
Distribusi Marriage by Zodiacs dalam bentuk Daigram Batang
library(ggplot2)
MarriageZod = read.csv("https://raw.githubusercontent.com/Bakti-Siregar/dataset/master/Bookdown-Data-Science-for-Beginners/Marriage.csv")
ggplot(MarriageZod, aes(x=zodiacs))+
geom_bar(fill='orchid', color='azure4')+
theme_minimal()+
labs(x="Zodiacs",
y="Frequency",
title = "Marriage Participants by Zodiac") Dalam Bentuk Persentase
library(ggplot2)
ggplot(MarriageZod,
aes(x=zodiacs,
y=..count.. / sum(..count..)))+
geom_bar(fill=rainbow(12), color='azure4')+
theme_light()+
labs(x="Zodiacs",
y="Frequency",
title = "Marriage Participants by Zodiac in Percents") scale_y_continuous(labels=scales::percent)## <ScaleContinuousPosition>
## Range:
## Limits: 0 -- 1
Bisa Juga dalam bentuk Sorting from lowest to highest
library(dplyr)
library(ggplot2)
plotdata = MarriageZod%>%
count(zodiacs)
ggplot(plotdata,
aes(x=reorder(zodiacs,n),
y = n))+
geom_bar(stat="identity",
fill=rainbow(12),
color="azure4" )+
theme_light()+ #theme yang berbeda dngan sblumnya
labs(x="Zodiacs",
y="Frequency",
title = "Sorted Marriage Participants by Zodiacs")Bar pada Chart dapat diberi label sesuai frekuensi atau persentase maisng-masing
library(dplyr)
library(ggplot2)
library(scales)
plotdata = MarriageZod%>%
count(zodiacs)%>%
mutate(pct=n / sum(n),
pctlabel = paste0(round(pct*100), "%"))
ggplot(plotdata,
aes(x= reorder(zodiacs, -pct),
y=pct)) +
geom_bar(stat="identity", fill = rainbow(12), color="azure4") +
geom_text(aes(label = pctlabel), vjust= -0.25) +
theme_classic() + #theme yang lainnya
scale_y_continuous(labels = percent) +
labs(x = "Zodiacs",
y = "Percentage",
title = "Labeled Bars") Label di bawah Tumpang tindih Bisa diatasi dengan memutar label pada sumbu x nya
library(ggplot2)
library(scales)
ggplot(plotdata,
aes(x= reorder(zodiacs, -pct),
y=pct)) +
geom_bar(stat="identity", fill = rainbow(12), color="azure4") +
geom_text(aes(label = pctlabel), vjust= -0.25) +
theme_minimal() + #theme yang lainnya
scale_y_continuous(labels = percent) +
labs(x = "Zodiacs",
y = "Percentage",
title = "Adjusted X and Labeled Bars")theme(axis.text.x = element_text(angle = 45, hjust=1))## List of 1
## $ axis.text.x:List of 11
## ..$ family : NULL
## ..$ face : NULL
## ..$ colour : NULL
## ..$ size : NULL
## ..$ hjust : num 1
## ..$ vjust : NULL
## ..$ angle : num 45
## ..$ lineheight : NULL
## ..$ margin : NULL
## ..$ debug : NULL
## ..$ inherit.blank: logi FALSE
## ..- attr(*, "class")= chr [1:2] "element_text" "element"
## - attr(*, "class")= chr [1:2] "theme" "gg"
## - attr(*, "complete")= logi FALSE
## - attr(*, "validate")= logi TRUE
Menukar Sumbu X dan Y (Memutar Grafik 90 derajat)
ggplot(plotdata,
aes(x= reorder(zodiacs, -pct),
y=pct)) +
geom_bar(stat="identity", fill = rainbow(12), color="azure4") +
geom_text(aes(label = pctlabel), vjust= -0.25) +
theme_minimal() +
scale_y_continuous(labels = percent) +
labs(x = "Zodiacs",
y = "Percentage",
title = "Rotated Bars")coord_flip()## <ggproto object: Class CoordFlip, CoordCartesian, Coord, gg>
## aspect: function
## backtransform_range: function
## clip: on
## default: FALSE
## distance: function
## expand: TRUE
## is_free: function
## is_linear: function
## labels: function
## limits: list
## modify_scales: function
## range: function
## render_axis_h: function
## render_axis_v: function
## render_bg: function
## render_fg: function
## setup_data: function
## setup_layout: function
## setup_panel_guides: function
## setup_panel_params: function
## setup_params: function
## train_panel_guides: function
## transform: function
## super: <ggproto object: Class CoordFlip, CoordCartesian, Coord, gg>
Pie Chart
Variasi dari Bar Chart yang merupakan Grafik berbentuk Lingkaran
library(dplyr)
library(ggplot2)
library(scales)
plotdata = MarriageZod%>%
count(race)%>%
arrange(desc(race)) %>%
mutate(prop=round(n*100/sum(n), 1),
lab.ypos = cumsum(prop)- 0.5*prop )
#Membuat Pie Chart
mycols = c("#0073C2FF", "#EFC000CF", "#868686FF", "#CD534CFF")
ggplot(plotdata, aes(x="", y = prop, fill = race )) +
geom_bar(width=1, stat = "identity", color = "white") +
coord_polar ("y", start = 0 ) +
geom_text (aes(y=lab.ypos, label = prop), color = "white")+
scale_fill_manual(values=mycols) +
theme_void() +
labs (title = "Marriage Participants by Race")Variasi bentuk dari Pie chart adalah Donut Chart, hanya beda bolong di tengahnya
library(ggplot2)
library(scales)
ggplot(plotdata, aes(x=2, y = prop, fill = race )) +
geom_bar(stat = "identity", color = "white") +
coord_polar (theta = "y", start = 0 ) +
geom_text(aes(y=lab.ypos, label = prop), color = "white")+
scale_fill_manual(values=mycols) +
theme_void() +
xlim(0.5, 2.5)+
labs (title = "Marriage Participants by Race")Menambahkan Labels pada Donut Chart
library(ggplot2)
library(scales)
plotdata$percent = paste0(plotdata$race, "\n",
round(plotdata$prop), "%")
ggplot(plotdata, aes(x=2, y = prop, fill = race )) +
geom_bar(stat = "identity", color = "white") +
coord_polar (theta = "y", start = 0 ) +
geom_text(aes(y=lab.ypos, label = prop), color = "white")+
scale_fill_manual(values=mycols) +
theme_void() +
xlim(0.5, 2.5)+
labs (title = "Marriage Participants by Race")Peta Pohon
Biasanya digunakan terhadap Kategorikal data yang memiliki banyak tingkatan
library(ggplot2)
library(treemapify)
library(scales)
plotdata = MarriageZod %>%
count(officialTitle)
ggplot(plotdata, aes(fill = officialTitle, area = n))+
geom_treemap()+
labs(title = " Marriage Participants by Officiate") With Labels
library(ggplot2)
library(treemapify)
library(scales)
plotdata = MarriageZod %>%
count(officialTitle)
ggplot(plotdata, aes(fill = officialTitle, area = n, label = officialTitle))+
geom_treemap()+
geom_treemap_text(color="white", place = "centre")+
labs(title = " Marriage Participants by Officiate")+
theme(legend.position="none")Variabel Kontinu
Biasanya data Numerik atau Angka digambarkan dengan Histogram, Plot Densitas kernel, dan Diagram Titik
Histogram
library(ggplot2)
ggplot(MarriageZod, aes(x=age)) +
geom_histogram(fill = "olivedrab4", color = "red", bins = 20) +
theme_minimal() +
labs(title = "Marriage Participants by Age (basic)", x="Age")Cara mengubah Binwidth atau Range yang diwakili oleh satu batang histogram
library(ggplot2)
library(scales)
ggplot(MarriageZod, aes(x=age, y = ..count../sum(..count..))) +
geom_histogram(fill = "deeppink3", color = "cyan1", binwidth = 5) +
theme_minimal() +
labs(title = "Marriage Participants by Age (Alternative Binds and bandwidths)", x="Age",
y = "Percent") +
scale_y_continuous(labels=percent) Dengan percent sebagai pengganti jumlah frekuensi
library(ggplot2)
library(scales)
ggplot(MarriageZod, aes(x=age, y = ..count../sum(..count..))) +
geom_histogram(fill = "lemonchiffon2", color = "orangered1", binwidth = 5) +
theme_minimal() +
labs(title = "Marriage Participants by Age (Alternative Binds and bandwidths)", x="Age",
y = "Percent") +
scale_y_continuous(labels=percent)Plot Density Kernel
versi diperhalus dari Histogram
library(ggplot2)
ggplot(MarriageZod, aes(x=age)) +
geom_density(fill = "plum3") +
theme_minimal() +
labs(title = "Marriage Participants by Age")Cara Membacanya adalah dengan menghitung luas dibawah kurva dari range area yang di inginkan.
Parameter Penghalusan (Smoothing)
Nilai dibawah default dengan fungsi “bw.nrd0” menghasilkan penghalusan sedikit, dan nilai yang lebih besar dari default menghasilkan penghalusan lebih banyak
library(ggplot2)
bw.nrd0(MarriageZod$age)## [1] 5.181946
ggplot(MarriageZod, aes(x=age)) +
geom_density (fill = "lightpink", bw=1) +
theme_minimal() +
labs (title = "Participants by Age", subtitle = "Bandwidth = 1 ")Diagram Titik (DotPlot)
Sebagai Alternatif dari Histogram
library(ggplot2)
ggplot(MarriageZod, aes(x=age)) +
geom_dotplot(fill = "palevioletred3", color = "azure4", binwidth=2)+
theme_minimal()+
labs (title = "Participants by Age", x = "Age" , y="Proportion" )Data Bivariat
Grafik yang dipengaruhi oleh dua variabel yang berhubungan
Kategorikal vs Kategorikal
Keduanya tidak dapat dihitung atau bukan numerik
Diagram batang Bertumpuk
Perbandingan antara Kelas Mobil dan penggeraknya (Front, rear, atau 4WD)
library(ggplot2)
mpg$drv = factor(mpg$drv,
levels= c("f", "r", "4"),
labels = c("Front-wheel", "Rear-wheel", "4-wheel"))
# Diagram Batang Bertumpuk
ggplot(mpg, aes(x= class, fill = drv))+
geom_bar(position = "fill") +
theme_minimal() +
labs(y="Proportion")Diagram Batang Dikelompokkan
Variabel kategori yang berbeda diletakkan di bar yang berbeda
library(ggplot2)
ggplot(mpg, aes(x=class, fill = drv)) +
theme_minimal() +
geom_bar(position=position_dodge(preserve = "single"))Diagram batang segmentasi
Kurang lebihnya miirp dengan diagram batang bertumpuk
library(ggplot2)
library(dplyr)
library(scales)
#RIngkasan dataset
plotdata = mpg%>%
group_by(class, drv) %>%
dplyr::summarize (n= n()) %>%
mutate(pct = n/sum(n),
lbl = scales::percent(pct))
ggplot(plotdata, aes(x=factor(class),
y=pct,
fill = factor(drv)))+
geom_bar(stat="identity", position="fill")+
scale_y_continuous(breaks = seq(0,1,0.2), label = percent)+
geom_text(aes(label=lbl), size= 3, position = position_stack(vjust = 0.5)) +
scale_fill_brewer (palette="Set2")+
theme_minimal()+
labs(y='Percent', fill = "Drivetrain",
x= "Class", title = "Automobile drives by class")+
theme_minimal()Mozaic Plot
Luas dari area menggambarkan proporsi jumlah kategorikal dengan kombinasi tertentu dengan warna ubin yang menunjukkan hubungan antar variabel. Contoh plot dengan data survival Titanic
tabel = xtabs(Freq ~ Survived + Class + Sex, Titanic)
ftable(tabel)## Sex Male Female
## Survived Class
## No 1st 118 4
## 2nd 154 13
## 3rd 422 106
## Crew 670 3
## Yes 1st 62 141
## 2nd 25 93
## 3rd 88 90
## Crew 192 20
library(vcd)
mosaic(tabel, main = "Titanic data")Dengan memberi warna pada ubin kita bisa tahu apakah nilainya sesuai dengan yang diharapkan jika berlaku tidak terikat
mosaic(tabel, shade = T, legens = T,
labelin_args = list(set_varnames = c(Sex= "Gender", Survives = "Survived",
Class = "PAssenger Class")),
set.labels = list(Survived = c("No",'Yes'),
Class = c("1st", "2nd", "3rd", "Crew"),
main = "Titanic Data"
))Dilihat dari warna, lebih banyak Crew Laki-laki tewas dan Penumbang Wanita dari ketiga kelas yang selamat dan sebaliknya. Jauh lebih sedikit penumpang First class yang tidak selamat baik laki-laiki atau perempuan.
Kontinu vs Kontinu
Dua variable numerik biasanya digambarkan dengan grafik sebaran titik atau g aris
Scatter Plot
library(ggplot2)
library(hrbrthemes)
#Make a Dataframe
d1 = data.frame(x=seq(1,100),
y=rnorm(100),
name = "No trend")
d2 = d1 %>%
mutate (y = x*10 + rnorm (100, sd=60)) %>%
mutate (name = "Linear relationship ")
d3 = d1 %>%
mutate(y=x^2 + rnorm(100, sd=140)) %>%
mutate (name = "Square")
d4 = data.frame(x=seq(1,10, 0.1),
y=sin(seq(1,10,0.1))+
rnorm(91, sd= 0.6))%>%
mutate(name = "Sin")
don <- do.call(rbind, list(d1, d2 ,d3, d4))
don %>%
ggplot(aes(x=x, y=y))+
geom_point(color = "#69b3a2", alpha = 0.8)+
theme_ipsum()+
facet_wrap(~name, scale = 'free')Contoh lain dengan Data Pengalaman Kerja dan Jumlah salary
library(carData)
library(ggplot2)
library(scales)
data(Salaries, package="carData")
ggplot(Salaries, aes(x=yrs.since.phd, y = salary))+
geom_point(color = "aquamarine2", size = 2, alpha = .8) +
scale_y_continuous (labels = scales ::dollar, limits = c(50000, 250000)) +
scale_x_continuous (breaks = seq(0,60,10),
limits=c(0,60))+
theme_minimal() +
labs (x = "Years since PhD",
y = "",
title = 'Experience vs Salary',
subtitle = "9-Months Salary for 2008-2009")Plot Sebaran Menyesuaikan Garis
Plot ini digunakan dengan batas kepercayaan mencapai 95%
library(ggplot2)
ggplot(Salaries, aes(x=yrs.since.phd, y=salary))+
geom_point(color="magenta")+
geom_smooth(method="lm", color="brown1")+
theme_minimal()+
labs(x="Years Since PhD", y = "",
title = 'Experience vs Salary',
subtitle = "9-Months Salary for 2008-2009")Benar bahwa gaji akan meningkat sejalan pengalaman , namun ada penurunan juga, garis lurus kurang pas lebih cocok garis melengkung. Biasanya garis melengkunf kuadrat atau pangkat tiga (kubik). garis polinomial lebih dari kubik jarang digunakan
library(ggplot2)
ggplot(Salaries, aes(x=yrs.since.phd, y=salary))+
geom_point(color="magenta")+
geom_smooth(method="lm",
formula = y~poly(x,2),
color="darkolivegreen1")+
theme_minimal()+
labs(x="Years Since PhD", y = "",
title = 'Experience vs Salary',
subtitle = "9-Months Salary for 2008-2009")Penghalusan Plot Sebaran
library(ggplot2)
ggplot(Salaries, aes(x=yrs.since.phd, y=salary))+
geom_point(color="magenta", size = 2, alpha = 1)+
geom_smooth(size = 1, color="deepskyblue1")+
scale_y_continuous(label = scales :: dollar ,
limits = c(50000, 250000))+
scale_x_continuous(breaks = seq(0,60,10),
limits = c(0,60))+
theme_minimal()+
labs(x="Years Since PhD", y = "",
title = 'Experience vs Salary',
subtitle = "9-Months Salary for 2008-2009")Kategorikal vs Kontinu
Diagram Batang
library(dplyr)
library(ggplot2)
library(scales)
data(Salaries, package = "carData")
plotdata = Salaries %>%
group_by(rank)%>%
dplyr ::summarize(mean_salary = mean(salary))
mycols = c("#CD534CFF", "#EFC000FF", "#0073C2FF")
ggplot(plotdata, aes(x=factor(rank, labels = c("Assistanst \n Professor", "Associate \n Professor", "Full \n Professor")),
y = mean_salary))+
geom_bar(stat="identity", fill = mycols) +
geom_text(aes(label = dollar(mean_salary)), vjust = -0.25)+
scale_y_continuous (breaks = seq(0,130000, 20000), label = dollar) +
theme_minimal()+
labs(title = "Mean Salary by Rank",
subtitle = "9-Month academic salary for 2008-2009",
x="", y="")Plot DEnsitas Kernel yang dikelompokkan
ggplot(Salaries, aes(x=salary, fill = rank ))+
geom_density(alpha=0.4)+
theme_minimal()+
labs(title = "Salary Distributions by Rank")Box Plot
Boxplot memberikan kita Five-Number Summary dari suatu data
mycols = c("#CD534CFF", "#EFC000FF", "#0073C2FF")
ggplot(Salaries, aes(x=rank, y=salary))+
geom_boxplot(notch = T, fill = mycols, alpha = .7)+
theme_minimal()+
labs(title = "Salary Distribution by Rank")Violin Plot
Mirip dengan Densitas Kernel, yang diputar 90 derajat dan diMirror
ggplot(Salaries, aes(x=rank, y = salary))+
geom_violin(fill = "azure1")+
geom_boxplot(width = 0.2,
fill = mycols,
outlier.color = "red",
outlier.size=2)+
theme_minimal()+
labs(title = "Salary Distribution by Rank")Plot Garis Punggung
Mirip dengan Plot Densitas Kernel, menampilkan distribusi kuantitas dari beberapa kelompok. dibuat dengan Library ggridges.Contoh penggunaaan dengan data Fuel Economy
library(dplyr)
library(ggplot2)
library(ggridges)
ggplot(mpg, aes(x=cty, y=class,
fill = class))+
geom_density_ridges(alpha=0.7)+
theme_ridges()+
labs("Highway Mileage by Auto Class")+
theme(legend.position = "none")Apabila Data terlalu tumpang tindih, bisa mengecilkan oppacity atau transparansi dengan mengecilkan nilai Alpha
Plot Garis
Gabungan dari Boxplot dan Line chart yang menghubungkan antar rata-rata (Titik Tengah Boxplot)
library(dplyr)
library(ggplot2)
library(ggridges)
#Menghitung Mean, StaDev, dan 95% Nilai Kepercayaan berdasarkan jabatan
plotdata = Salaries %>%
group_by(rank, sex)%>%
dplyr::summarize(n=n(),
mean = mean(salary),
sd= sd(salary),
se = sd/sqrt(n),
ci = qt(0.975, df = n-1) * sd/sqrt(n))
pd = position_dodge(0.2)
ggplot(plotdata, aes(x=factor(rank,
labels = c("Assistanst \n Professor", "Associate \n Professor", "Full \n Professor")), y = mean, group = sex, color = sex))+
geom_point(position = pd, size = 3) +
geom_line(position = pd, size = 1)+
geom_errorbar(aes(ymin=mean-se, ymax = mean + se),
width = .1 , position = pd, size = 1)+
scale_y_continuous(label = scales::dollar)+
scale_color_brewer(palette = "Set1")+
theme_minimal()+
labs(title = "Mean Salary by Rank and Sex",
subtitle= "(mean+/- standard error)",
x= "", y="", color = "Gender")Strip Plot
Scatter Plot yang dikelompokkan, agak susah dilihat apabila titiknya goyah
library(ggplot2)
library(scales)
ggplot(Salaries, aes(y=factor(rank,
labels = c("Assistanst \n Professor", "Associate \n Professor", "Full \n Professor")), x= salary, color= rank))+
geom_jitter(alpha = 0.7, size = 1.5)+
scale_x_continuous(label=dollar)+
theme_minimal()+
labs(title = "Academic Salary by Rank ",
subtitle= "9 Months Salary for 20008-2009 ",
x= "", y="")theme(legend.position = "none")## List of 1
## $ legend.position: chr "none"
## - attr(*, "class")= chr [1:2] "theme" "gg"
## - attr(*, "complete")= logi FALSE
## - attr(*, "validate")= logi TRUE
Gabungan Jitter dan Plot Kotak
Menambahkan plot kotak ke plot Jitter memudahkan presentasi distribusi
library(ggplot2)
library(scales)
ggplot(Salaries, aes(x= factor(rank,
labels = c("Assistanst \n Professor", "Associate \n Professor", "Full \n Professor")), y = salary , color = rank))+
geom_boxplot(size = 1,
outlier.shape = 1,
outlier.color = 'black',
outlier.size = 3)+
geom_jitter(alpha = 0.5,
width=.2)+
scale_y_continuous(label=dollar)+
theme_minimal()+
labs(title = "Academic Salary by Rank ",
subtitle= "9 Months Salary for 2008-2009 ",
x= "", y="")+
theme(legend.position = "none")+
coord_flip()Dalam geo_boxjitter kita bisa membuat plot hybrid kotak dan sebaran dalam library ggpol
library(ggplot2)
library(scales)
library(ggpol)
ggplot(Salaries, aes(x= factor(rank,
labels = c("Assistanst \n Professor", "Associate \n Professor", "Full \n Professor")), y = salary ,fill = rank))+
geom_boxjitter(color = 'black',
jitter.color = "darkgrey",
errorbar.draw = T)+
scale_y_continuous(label=dollar)+
labs(title = "Academic Salary by Rank ",
subtitle= "9 Months Salary for 2008-2009 ",
x= "", y="")+
theme_minimal()+
theme(legend.position = "none")Plot Kawanan Lebah
Mirip dengan Plot Biola dan Plot Jitter. Menunjukkan distribusi variabel kuantitatif dan densitas tiap titik
library(ggplot2)
library(scales)
library(ggbeeswarm) #mengurangi tumpang tindih
ggplot(Salaries, aes(x= factor(rank,
labels = c("Assistanst \n Professor", "Associate \n Professor", "Full \n Professor")), y = salary ,color = rank))+
geom_quasirandom(alpha = 0.7, size = 1.5)+
scale_y_continuous(label=dollar)+
labs(title = "Academic Salary by Rank ",
subtitle= "9 Months Salary for 2008-2009 ",
x= "", y="")+
theme_minimal()+
theme(legend.position = "none")Diagram Titik Cleveland
Digunakan ketika membandingkan statistik numerik sejumlah kelompok. Disebut juga Lolipop Graph. Contohnya data dari gapminder tentang harapan hidup di Asia
library(ggplot2)
library(dplyr)
library(scales)
library(ggbeeswarm)
library(gapminder)
data(gapminder, package = "gapminder")
#Subset hanya data Region Asia
library(dplyr)
plotdata = gapminder%>%
filter(continent == 'Asia' & year == 2007)
#Plot Cleveland
ggplot(plotdata, aes(x=lifeExp, y=reorder(country, lifeExp)))+
geom_point(color='navy', size=2)+
geom_segment(aes(x=40,
xend = lifeExp,
y=reorder(country, lifeExp),
yend=reorder(country, lifeExp)), color = 'azure3') +
labs (x = "Life Expectancy (years)",
y = "",
title = "Life Expectancy by Countries",
subtitle = "GapMinder data for Asia - 2007")+
theme_minimal()+
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank())Data Multivariat
Grafik Multivariat mempresentasikan hubungan antara lebih dari dua variabel, seperti membandingkan lebih dari dua grafik . Pada Multivariat ini, terdapat dua metode umum yaitu pengelompokan dan faceting.
Pengelompokan
Nilai dari dua variabel pertama dipetakan ke sumbu x dan y variabel tambahan juga digambarkan sesauai karakteristik visualnya, seperti warna, bentuk, ukuran, jenis garis, dan transparansi. Pengelompokan juga memplot lebih dari dua data ke dalam suatu grafik. Contohnya adalah dengan kita ingin memplot data menggunakan data set Salaries, mari kita tampilkan hubungan antara yrs.since.phd dan salary.
library(carData)
library (ggplot2)
data(Salaries, package="carData")
ggplot(Salaries, aes(x = yrs.since.phd,
y = salary,
color=rank)) +
geom_point() +
theme_minimal() +
labs(title = "Academic salary by rank and years since degree")Selanjutnya, tambahkan jenis kelamin profesor, menggunakan bentuk titik yang berbeda untuk menunjukkan jenis kelamin. Lalu meningkatkan ukuran titik dan menambahkan transparansi untuk memperjelas masing-masing titik .
library(carData)
library(ggplot2)
ggplot(Salaries, aes(x = yrs.since.phd,
y = salary,
color = rank,
shape = sex)) +
geom_point (size = 3, alpha = .6) +
theme_minimal() +
labs(title = "Academic salary by rank, sex, and years since degree")Grafik sepertinya terlalu ramai, FAceting akan lebih cocok. Pemetaan variabel ada dalam fungsi aes dan nilai konstanta lain di luarnya. Berikut Plot Gelembung dengan besar gelembung menentukan lama nya pengalaman kerja.
library(carData)
library(ggplot2)
ggplot(Salaries, aes(x = yrs.since.phd,
y = salary,
color = rank,
size = yrs.service)) +
geom_point (alpha = .8) +
theme_minimal() +
labs(title = "Academic salary by rank, sex, and years since degree")Dari grafik di atas, menjelaskan bahwa lama setelah menyandang Ph.D dan jabatan berkorelasi positif. Sebagai contoh terakhir, presentasi data yrs.since.phd vs. salary dan tambahkan jenis kelamin menggunakan warna dan garis kuadrat yang paling cocok.
library(carData)
library(ggplot2)
ggplot(Salaries,
aes(x = yrs.since.phd,
y = salary,
color = sex)) +
geom_point(alpha = .4,
size = 3) +
geom_smooth(se=FALSE,
method = "lm",
formula = y~poly(x,2),
size = 1.5) +
labs(x = "Years Since Ph.D.",
title = "Academic Salary by Sex and Years Experience",
subtitle = "9-month salary for 2008-2009",
y = " ",
color = "Sex") +
scale_y_continuous(label = scales::dollar) +
scale_color_brewer (palette = "Set1") +
theme_minimal()Faceting atau pembagian faset
Membandingkan grafik satu dengan yang lainnya dengan x dan y atau x dan y dengan jangkauan yang sama
library(carData)
library(ggplot2)
ggplot(Salaries,
aes(x = salary)) +
geom_histogram(fill = "khaki3", color = 'white')+
facet_wrap(~rank, ncol=1) +
theme_minimal()+
labs(title = "Salary Histograms by rank")Facet_wrap berfungsi sebagai pemisah grafik dan opsi ncol sebagai pengatur jumlah kolom. Di COntoh kedua menggunakan 2 variabel sebagai facet yaitu jenis kelamin dan jabatan.
library(carData)
library(ggplot2)
ggplot(Salaries,
aes(x = salary/1000)) +
geom_histogram(fill = "mediumpurple3", color = 'white')+
facet_grid(sex~rank) +
theme_minimal()+
labs(title = "Salary Histograms by Sex and rank",
x = "Salary($1000)")Contohnya menggunakan Plot Mean/SE dan pembagian faset untuk membandingkan gajigaji dari profesor pria dan wanita, dalam jabatan dan disiplin ilmu. Kita akan menggunakan warna untuk membedakan jenis kelamin dan pembagian faset untuk membuat plotjabatan berdasarkan kombinasi disiplin ilmu.
library(carData)
library(ggplot2)
library (dplyr)
#Menghitung Rata-rata dan Kesalahan Standar
plotdata <- Salaries %>%
group_by (sex, rank, discipline) %>%
dplyr :: summarize (n = n(),
mean = mean(salary),
sd = sd(salary),
se = sd / sqrt(n))
#Membuat label yang lebih baik untuk disiplin ilmu
plotdata$discipline <- factor(plotdata$discipline,
labels = c("Theoretical",
"Applied"))
#Membuat Plot
ggplot(plotdata,
aes(x = sex,
y = mean,
color = sex)) +
geom_point(size = 3) +
geom_errorbar(aes (ymin = mean - se,
ymax = mean + se),
width = .1) +
scale_y_continuous (breaks = seq(70000, 140000, 10000),
label = scales::dollar) +
facet_grid(.~ rank + discipline) +
theme_bw() +
theme (legend.position = "none",
panel.grid.major.x = element_blank(),
panel.grid.minor.y = element_blank()) +
labs(x="",
y="",
title="Nine month academic salaries by gender, discipline, and rank",
subtitle = "(Means and standard errors)") + scale_color_brewer (palette="Set1")- facet_grid(~rank+dicipline) tidak menentukan variabel baris kombinasi jabatan dan disiplin ilmu.
- theme() -> membuat tema hitam dan putih, menghilangkan garis grid vertikal, dan garis grid horizontal minor.
- scale_color_brewer() -> mengubah skema warna untuk titik dan batang batang kesalahan.
Kalau dilihat, adanya perbedaan antara gender dan gaji Associate dan Full Professors di bidang teoritis. ini bisa terjadi karena kita tidak melihat secara langsung mengapa ada perbedaan tersebut. Mungkin diperlukan percobaan secara langsung agar kita mengetahui .
Contoh terakhir, kita coba menggunakan dataset baru dan memplot perubahan dalam harapan hidup dari waktu ke waktu untuk negara-negara di Asia. Data tersebut berasal dari dataset gapminder dalam package gapminder. Setiap negara akan muncul dalam fasetnya sendiri.
Fungsi tema -> menyederhanakan warna latar belakang, memutar teks sumbu x, dan memperkecil ukuran tulisan
library(gapminder)
library(ggplot2)
library (dplyr)
# memplot harapan hidup berdasarkan tahun secara terpisah untuk setiap negara di Asia
data(gapminder, package = "gapminder")
# Pilih data Asia
plotdata <- dplyr::filter (gapminder,
continent == "Asia")
# memplot harapan hidup berdasarkan tahun, untuk setiap negara
ggplot(plotdata, aes (x=year, y = lifeExp)) +
geom_line (color="grey") +
geom_point(color="blue") +
facet_wrap(~country) +
theme_minimal(base_size = 9) +
theme (axis.text.x = element_text(angle = 45,
hjust = 1)) +
labs (title = "Changes in Life Expectancy",
x = "Year", y = "Life Expectancy")