Penggunaan Ggplot2 untuk Membuat Grafik Scatter dan Density
Gambar Placeholder
{{ad_middle}}
Langkah-Langkah Membuat Grafik Scatter dan Density
Step 1/3. Load Library and Create Data Frame
Sebelum membuat grafik, kita perlu load library ggplot2 dan create data frame. Berikut adalah contoh data frame yang digunakan dalam analisis ini:
install.packages("ggplot2")
library(ggplot2)
df <- read.csv("data.csv") # replace with your own data file
Step 2/3. Create the Plots
Dalam langkah ini, kita akan membuat beberapa plot menggunakan library ggplot2. Berikut adalah contoh plot yang dibuat:
# Scatter plot of x and y variables
scatterPlot <- ggplot(df,aes(x, y, color=group)) +
geom_point() +
scale_color_manual(values = c('#999999','#E69F00')) +
theme(legend.position=c(0,1), legend.justification=c(0,1))
scatterPlot
# Marginal density plot of x (top panel)
xdensity <- ggplot(df, aes(x, fill=group)) +
geom_density(alpha=.5) +
scale_fill_manual(values = c('#999999','#E69F00')) +
theme(legend.position = "none")
xdensity
# Marginal density plot of y (right panel)
ydensity <- ggplot(df, aes(y, fill=group)) +
geom_density(alpha=.5) +
scale_fill_manual(values = c('#999999','#E69F00')) +
theme(legend.position = "none")
ydensity
Step 3/3. Put the Plots Together
Dalam langkah ini, kita akan menggabungkan beberapa plot yang dibuat sebelumnya menggunakan library gridExtra. Berikut adalah contoh bagaimana kita dapat menggabungkan beberapa plot pada halaman yang sama:
library("gridExtra")
grid.arrange(xdensity, blankPlot, scatterPlot, ydensity,
ncol=2, nrow=2, widths=c(4, 1.4), heights=c(1.4, 4))
Customized Scatter Plots
Basic Scatter Plot
ggplot(mtcars, aes(x=wt, y=mpg)) +
geom_point()+
geom_smooth(method=lm, color="black")+
labs(title="Miles per gallon \n according to the weight",
x="Weight (lb/1000)", y = "Miles/(US) gallon")+
theme_classic()
Change Color/Shape by Groups
p <- ggplot(mtcars, aes(x=wt, y=mpg, color=cyl, shape=cyl)) +
geom_point()+
geom_smooth(method=lm, se=FALSE, fullrange=TRUE)+
labs(title="Miles per gallon \n according to the weight",
x="Weight (lb/1000)", y = "Miles/(US) gallon")
p + theme_classic()
Change Colors Manually
Kita dapat mengubah warna secara manual menggunakan library ggplot2. Berikut adalah contoh bagaimana kita dapat mengubah warna:
# Continuous colors
p + scale_color_brewer(palette="Paired") + theme_classic()
# Discrete colors
p + scale_color_brewer(palette="Dark2") + theme_minimal()
# Gradient colors
p + scale_color_brewer(palette="Accent") + theme_minimal()
Informasi
Analisis ini telah dilakukan menggunakan software R (ver. 3.2.4) dan ggplot2 (ver. 2.1.0).