Using either penguins or diamonds:
Create a faceted plot: - Example: distribution or scatterplot - Create one using facet_wrap, and one using facet_grid in the layout that makes the most sense Make sure: - Labels are clear - Colors are readable - Theme is clean
# library
library(ggplot2)
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(tidyr)
#install.packages(patchwork)
library(patchwork)
# data
data("penguins")
#View(penguins)
penguins_clean <- penguins %>%
drop_na()
#View(penguins_clean)
# wrap plot
wrap_p <- ggplot(penguins_clean, aes(bill_len, bill_dep, fill = species)) +
geom_violin(alpha = 0.5) +
facet_wrap(~ island) +
labs(
title = "Bill Length Vs Depth Per Island",
x = "Bill Length",
y = "Bill Depth",
fill = "Species"
) +
theme_minimal()
wrap_p
# grid plot
grid_p <- ggplot(penguins_clean, aes(bill_len, bill_dep, fill = species)) +
geom_violin(alpha = 0.5) +
facet_grid(sex ~ island) +
labs(
title = "Bill Length Vs Depth Per Island and Sex",
x = "Bill Length",
y = "Bill Depth",
fill = "Species"
) +
theme_minimal()
grid_p
try - Side-by-side layout - Stacked layout - Unequal sizes
# library
library(ggplot2)
# data
data("penguins")
#View(penguins)
penguins_clean <- penguins %>%
drop_na()
#View(penguins_clean)
# scatterplot
p1 <- ggplot(penguins_clean, aes(flipper_len, body_mass, color = species)) +
geom_point(alpha = 0.7, size = 2) +
labs(
title = "Flipper Length vs Body Mass",
x = "Flipper Length",
y = "Body Mass",
color = "Species"
) +
theme_minimal()
p1
# boxplot
p2 <- ggplot(penguins_clean, aes(species, bill_len, fill = species)) +
geom_col() +
labs(
title = "Bill Length by Species",
x = "Species",
y = "Bill Length",
fill = "Species"
) +
theme_minimal()
p2
# density plot
p3 <- ggplot(penguins_clean, aes(body_mass, fill = species)) +
geom_density(alpha = 0.5) +
labs(
title = "Density of Body Mass",
x = "Body Mass (g)",
y = "Density",
fill = "Species"
) +
theme_minimal()
p3
# combined figure
combined_plot1 <- p1 + p2 + p3
combined_plot1
combined_plot2 <- p1 / p2 / p3
combined_plot2
combined_plot3 <- (p1 + p2) / p3
combined_plot3
Please write code to perform each of these functions.
Export your combined figure: - As a PNG (300 dpi) - As a PDF Export your dataframe as a CSV file, and your PNG as an image.
# export combined figure as PNG
ggsave(filename = "combined_penguins_figure.png",
plot = combined_plot3,
dpi = 300)
## Saving 7 x 5 in image
# export combined figure as PDF
ggsave(filename = "combined_penguins_figure.pdf",
plot = combined_plot3)
## Saving 7 x 5 in image
# export data frame as CSV
write.csv(penguins_clean, "penguins_clean.csv", row.names = F)