Practice Task 1 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
install.packages("ggplot2")
## Installing package into '/cloud/lib/x86_64-pc-linux-gnu-library/4.5'
## (as 'lib' is unspecified)
install.packages("patchwork")
## Installing package into '/cloud/lib/x86_64-pc-linux-gnu-library/4.5'
## (as 'lib' is unspecified)
library(ggplot2)
library(patchwork)
data(diamonds)
head(diamonds)
## # A tibble: 6 × 10
## carat cut color clarity depth table price x y z
## <dbl> <ord> <ord> <ord> <dbl> <dbl> <int> <dbl> <dbl> <dbl>
## 1 0.23 Ideal E SI2 61.5 55 326 3.95 3.98 2.43
## 2 0.21 Premium E SI1 59.8 61 326 3.89 3.84 2.31
## 3 0.23 Good E VS1 56.9 65 327 4.05 4.07 2.31
## 4 0.29 Premium I VS2 62.4 58 334 4.2 4.23 2.63
## 5 0.31 Good J SI2 63.3 58 335 4.34 4.35 2.75
## 6 0.24 Very Good J VVS2 62.8 57 336 3.94 3.96 2.48
pl1=ggplot(diamonds,aes(x=carat,y=price,color=cut))
pl1=pl1+geom_point()
pl1=pl1+facet_wrap(~cut)
pl1=pl1+labs(title="scatter plot that shows facet wrap by price and cut")
pl1=pl1+theme_bw()
pl1
pl2=ggplot(diamonds,aes(x=carat,y=price,color=cut))
pl2=pl2+geom_point()
pl2=pl2+facet_grid(color~cut)
pl2=pl2+labs(title="scatter plot that shows facet grid by price and cut with the gird being color by cut")
pl2=pl2+theme_bw()
pl2
# Part 2 Practice Task 2 Create 3–4 different plots (e.g., scatterplot,
barplot, density plot) Combine them into a single multi-panel figure
using patchwork/ggforce Make sure you collect the legends when
appropriate.
Try:
Side-by-side layout Stacked layout Unequal sizes
install.packages("patchwork")
## Installing package into '/cloud/lib/x86_64-pc-linux-gnu-library/4.5'
## (as 'lib' is unspecified)
library(patchwork)
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(ggforce)
point_plot= diamonds %>%
ggplot(aes(x=carat,y=price,color=cut))+
geom_point()
point_plot
point_plot2= diamonds %>%
ggplot(aes(x=cut,fill=cut))+
geom_bar()
point_plot2
point_plot3=diamonds %>%
ggplot(aes(x=cut,fill=cut))+
geom_density()
point_plot3
p=(point_plot+point_plot2)/point_plot3
p+
plot_layout(guides = "collect")&theme(legend.position = "top")
# Part 3 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.
p
ggsave("patchworkplot.png")
## Saving 7 x 5 in image
ggsave("patchworkplot.pdf")
## Saving 7 x 5 in image
write.csv(diamonds,file="diamond_df.csv",row.names=FALSE)