Quadrant Plot Data
# Load the data
data(iris)
head(iris)
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1 5.1 3.5 1.4 0.2 setosa
## 2 4.9 3.0 1.4 0.2 setosa
## 3 4.7 3.2 1.3 0.2 setosa
## 4 4.6 3.1 1.5 0.2 setosa
## 5 5.0 3.6 1.4 0.2 setosa
## 6 5.4 3.9 1.7 0.4 setosa
Data Processing
# Calculate midpoints for the x-axis and y-axis
x_mid <- mean(c(max(iris$Petal.Length, na.rm = TRUE), min(iris$Petal.Length, na.rm = TRUE)))
y_mid <- mean(c(max(iris$Petal.Width, na.rm = TRUE), min(iris$Petal.Width, na.rm = TRUE)))
# Create a new column 'quadrant' in the iris data
iris2 <- iris %>% mutate(quadrant = case_when(
Petal.Length > x_mid & Petal.Width > y_mid ~ "Q1",
Petal.Length <= x_mid & Petal.Width > y_mid ~ "Q2",
Petal.Length <= x_mid & Petal.Width <= y_mid ~ "Q3",
TRUE ~ "Q4"
))
head(iris2)
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species quadrant
## 1 5.1 3.5 1.4 0.2 setosa Q3
## 2 4.9 3.0 1.4 0.2 setosa Q3
## 3 4.7 3.2 1.3 0.2 setosa Q3
## 4 4.6 3.1 1.5 0.2 setosa Q3
## 5 5.0 3.6 1.4 0.2 setosa Q3
## 6 5.4 3.9 1.7 0.4 setosa Q3
Summary Table
# Create a summary table 'iris_labels'
iris_labels <- iris2 |>
count(quadrant) |>
mutate(x = if_else(quadrant %in% c("Q1", "Q4"), Inf, -Inf),
hjust = if_else(quadrant %in% c("Q1", "Q4"), 1, 0),
y = if_else(quadrant %in% c("Q1", "Q2"), Inf, -Inf),
vjust = if_else(quadrant %in% c("Q1", "Q2"), 1, 0))
head(iris_labels)
## quadrant n x hjust y vjust
## 1 Q1 71 Inf 1 Inf 1
## 2 Q2 1 -Inf 0 Inf 1
## 3 Q3 60 -Inf 0 -Inf 0
## 4 Q4 18 Inf 1 -Inf 0
Quadrant Plot
# Create a scatter plot with quadrant color-coding
ggplot(iris2, aes(x = Petal.Length, y = Petal.Width, color = quadrant)) +
geom_vline(xintercept = x_mid) +
geom_hline(yintercept = y_mid) +
geom_point() +
# Add labels to the plot based on the summary table 'iris_labels'
geom_label(data = iris_labels,
aes(label = paste0("n = ", n),
x = x, y = y, color = NULL,
hjust = hjust, vjust = vjust),
fill = NA, label.size = 0,
show.legend = FALSE) +
labs(title = "Quadrant Plot of Iris Data",
x = "Petal Length",
y = "Petal Width")
