The base R reorder() function changes a factor’s ordering using values from another variable or expression. In ggplot2, it makes categorical axes follow a meaningful measure instead of default factor order. section 6.4.1
Use reorder() when a chart should rank categories by a computed measure:
- Write reorder(Q1vF, -n) to order Q1vF by counts in descending order. section 6.4.1
- Write reorder(Q1vF, -pct_total) to order the same factors by winning percentage. section 6.4.1
- Omit the minus operator to sort in ascending order. section 6.4.1
plot1a <- ggplot(tbl1, aes(x = reorder(Q1vF, -n), y = n)) +
geom_bar(color = c("orange1", "orange1", "gray74", "gray74"),
fill = c("orange1", "orange1", "gray74", "gray74"),
stat = "identity") +
labs(title = "Teams Winning the First Quarter",
subtitle = "Win-Loss Record = 1,333-657",
x = "Win Combinations",
y = "Wins") +
geom_text(aes(x = Q1vF, y = n, label = n, vjust = -0.3,
fontface = "bold")) +
theme(plot.title = element_text(face = "bold"))
plot1b <- ggplot(tbl1, aes(x = reorder(Q1vF, -pct_total), y = pct_total)) +
geom_bar(color = c("orange1", "orange1", "gray74", "gray74"),
fill = c("orange1", "orange1", "gray74", "gray74"),
stat = "identity") +
labs(title = "Teams Winning the First Quarter",
subtitle = "Winning Percentage = 66.98%",
x = "Win Combinations",
y = "Winning Percentage") +
geom_text(aes(x = Q1vF, y = pct_total, label = pct_total,
vjust = -0.3, fontface = "bold")) +
theme(plot.title = element_text(face = "bold"))
Compare two bar charts that reorder the same Q1vF categories by counts and percentages. section 6.4.1
Ranking NBA win combinations
A chart of first-quarter and full-game outcomes becomes easier to read when HH, RR, RH, and HR are ranked by n or pct_total. The resulting order highlights the most common combinations first and supports direct comparison between counts and winning percentages. section 6.4.1
