Use geom_bar() to turn categorical data into rectangular bars. By default, it counts rows for each x value; stat = "identity" instead uses the supplied y values. section 14.3
A typical workflow combines data preparation with visual annotations:
- Summarize observations first when the chart should show means, medians, totals, or percentages rather than row counts. section 3.5.1 section 14.3
- Map the category to x and the measured result to y, then add stat = "identity" so bar heights follow that result. section 3.5.1 section 14.3
- Adjust width, colors, axis limits, category order, and labels with width, fill, color, ylim(), scale_x_discrete(), geom_text(), and geom_label(). section 3.5.1
- Combine geom_bar() with facet_wrap() to compare the same bar measure across mutually exclusive panels. section 9.5.2
NBA scoring by season
After computing average points per game for each season, plot the result with: ggplot(first_tibble, aes(x = season, y = pts_avg)) + geom_bar(stat = "identity", width = .5, color = "steelblue4", fill = "steelblue1") + geom_text(aes(label = pts_avg, vjust = -0.3)) + ylim(0, 110). The resulting chart compares ten NBA seasons, with labels above the bars; the displayed averages range from 96.3 in 2012 to 105.6 in 2017.
ggplot(first_tibble, aes(x = season, y = pts_avg)) +
geom_bar(stat = "identity", width = .5,
color = "steelblue4", fill = "steelblue1") +
labs(title = "Average Points per Game per Team by Season",
subtitle = "2008-17",
x = "Season",
y = "Average Points per Game") +
geom_text(aes(label = (pts_avg), vjust = -0.3, fontface = "bold")) +
ylim(0, 110) +
theme(plot.title = element_text(face = "bold"))
Browse the complete seasonal bar-chart listing, including labels, axis limits, titles, and styling. section 14.3
