liveBook · Manning

Geom_bar() function

As explained in Statistics Slam Dunk

The ggplot2 geom_bar() function creates bar layers whose heights represent counts or supplied values according to the selected statistical transformation.

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

How Statistics Slam Dunk covers it

How deep it goes
Explains default counting, supplied-value heights, styling, ordering, labels, axis limits, and faceting through executable examples.
Examples
Demonstrates NBA draft segments, home-away wins by days-off permutations, and seasonal average points per game.
What it assumes
Assumes basic R, ggplot2 aesthetics, and grouped data; demonstrates summarization with dplyr before plotting.
What you can do after
Build bar charts from counts or summarized values, annotate them, control their axes, and arrange comparisons with facets.
How it connects
Connects bar charts to ggplot2, statistical transformations, dplyr summarization, annotations, discrete scales, and facet plots.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Statistics Slam Dunk. The section links point to the parts of the book it draws on.