```{r setup}
library(tidyverse)
library(tidylog) # Debug tool that tells you what datas are
omitted and why
library(janitor) # Clean spaces in names
data<-read_csv("./data/Seattle_Pet_Licenses.csv",
col_types="ccccccc")
|> clean_names()
|> get_dupes(df, col1, col2) # Get duplicated rows and count,
may/not specify columns of interested
library(lubridate) # Changing the format of <date>
data$license_issue_date <- data$license_issue_date |> mdy() #
month-day-year
library(cowplot) # Juxtapose multiple plots
plot_grid(plot_grid(plot1,
plot2,
plot3,
nrow=3),
plot4,
rel_widths = c(1, 2)) # Distinguishing major and minor
plots
library(dplyr)
library(tidyr) # pivoting rows into columns to avoid
duplicate rows
pivot_wider( names_from = coloumn, values_from = column)
library(ggridges) # For ridge line plot (a voilin plot cut in half,
for more space)
geom_density_ridges(alpha = 0.5)
library(scales)
library(GGally) # Love this function, cross-comparing multiple
factors at once with p-value
p <- data |> ggpairs(
columns = c('income2', 'wtkg3', 'htm4',
'x_ageg5yr') # columns = takes in variables/factors
)
```
# ggplot2 will render plots in order by FACTORS, overlooking
‘LEVELS’ attributes
# Pulling out factors
data$Species <- [Link](data$Species) # Species is the name of
a column
freq$`ZIP Code` <- as_factor(freq$`ZIP Code`) # Backtick to enclose
names with spaces
# Reordering the factors according to frequency
```{r}
data <- data |>
group_by(Species) |>
mutate(frequency=n())
data$Species <- fct_reorder(data$Species, data$frequency)
# fct_reorder(reorder former, by latter)
# Always in ascending order
head(data$Species)
```
# Or in descending order
```{r}
data$Species <- data$Species |> fct_infreq()
head(data$Species)
```
# First ggplot
```{r}
ggplot() +
layer(data=freq,
mapping=aes(x=`ZIP Code`, y=total, fill=scope), # Optional
fill
# fill = interaction(f1, f2)
pull in >1 factors to create a coloured bars
geom='col',
stat='identity', # stat=’count’ to transform y-axis
into counting how many licences
# instead of the numerical
order of the licenses
position='identity')
+
labs(title=‘Your Chart Title’, caption=‘Your Chart Caption’)
+
xlab(’Title of X-axis’)
+
ylab(’Title of Y-axis’)
+
facet_wrap(vars(col_name), ncol = 3) # Like plot grid, but
shares the base layers (i.e. data filter etc.)
# facet_grid(rows
= var(), cols = vars()) is a plot inside a plot
```
# Or an equivalent helper function “geom_”
ggplot() +
geom_col(data=freq, mapping=aes(x=`ZIP Code`, y=total,
fill=scope))
# Make a Histogram instead
ggplot() +
geom_histogram(binwidth = 5) + # This is the width of each bar
geom_density() # This creates a Kernal Density Estimation
(KDE) plot for this data
# Function to set scope of x- or y-axis
ggplot(line_data, aes(x=license_issue_date)) +
geom_line(aes(color=species), stat="count") +
scale_x_date(limits = [Link](c("2020-01-01", NA)), date_breaks =
‘5 years’)
# scale_axis_DataType(limits = [Link]( c(“lower
limit”, “upper limit”) ))
scale_y_continuous(limits = 55, NA)
# Grouping small groups into one
# First, select and unlist the factor
to_recode<-freq |> filter(total<1000) |> select(`ZIP Code`) |>
unlist()
# Then, rename `ZIP Code` to “small” if it is in “to_recode” # set
membership
# Otherwise, keep the original characters TRUE ~ [Link]()
freq <- freq |>
mutate(`ZIP Code` = case_when(`ZIP Code` %in% to_recode ~
"small",
TRUE ~ [Link](`ZIP Code`)))
# You can flip the x-axis and y-axis by
gg_plot <- gg_plot + coord_flip() # Adding an extra flipped layer
onto it
# Such as flipping it into
a vertical population pyramid
# Population pyramid side-by-side histogram hacker code
# Now a quick mutate to change the population values for women to
be negative
grouped_data <- grouped_data |>
mutate(population = ifelse(x_sex==women, -population,
population))
# Forecasting using a linear model
# You can do so by adding a linear model layer on top of the
original ggplot
ggplot() +
geom_smooth(method = "lm", fullrange = TRUE, se =
FALSE, linetype = "dashed")
# This function/layer inherits data and scales of the
previous layers.
# fullrange plots beyond the data we have (i.e.
forecasting), and
# se means standard error (which is usually set TRUE
to display a range).