ggplot() initializes a ggplot2 plot object: the foundation for a layered visualization. Supply a data source first, then use aes() to map data variables to visual properties such as the x- and y-axes or fill. Add geometric layers, labels, scales, and themes with + to turn that foundation into a finished chart. section 2.5.3 section 2.5.4
A practical ggplot() workflow is:
- Pass the analysis data frame to ggplot(). section 2.5.3
- Define variable mappings inside aes(), such as aes(x = WS) for career win shares. section 2.5.3
- Add a geom with + to specify how values are drawn, such as geom_histogram(), geom_boxplot(), geom_tile(), or geom_text(). section 2.5.3 section 2.5.4
- Add presentation layers such as labs(), theme(), and a scale function; assign the result to an object and print it when needed. section 2.5.3 section 2.5.4
Histogram of NBA career win shares
Start with draft data and map WS to x. geom_histogram() divides the continuous values into bins and counts observations; labs() supplies the chart text, and theme() bolds the title. The resulting distribution gives a fast visual read of career win shares that would be difficult to get from rows of data alone. section 2.5.3
p1 <- ggplot(draft, aes(x = WS)) +
geom_histogram(fill = "royalblue3", color = "royalblue3",
bins = 8) +
labs(title = "Career Win Shares Distribution of
NBA First-Round Selections",
subtitle = "2000-09 NBA Drafts",
x = "Career Win Shares",
y = "Frequency") +
theme(plot.title = element_text(face = "bold"))
print(p1)
This complete plot shows the basic pattern: initialize with ggplot(draft, aes(x = WS)), then add a histogram, labels, and a theme with +. section 2.5.3
Correlation heat map
After correlations are reshaped into Var1, Var2, and value columns, ggplot() maps the two variable names to position and the correlation coefficient to fill. geom_tile() draws the matrix, while a two-color gradient and text labels make the direction and strength of associations readable. section 2.5.4
p4 <- ggplot(data = draft_cor, aes(x = Var1,
y = Var2, fill = value)) +
geom_tile() +
scale_fill_gradient2(midpoint = 0.5, mid = "grey84",
limits = c(-1, 1)) +
labs(title = "Correlation Matrix",
subtitle = "Correlation Coefficients between
Win Shares and Other Continuous Variables",
x = "",
y = "",
fill = "Correlation\nCoefficient",
caption = "Source: draft data set") +
theme(plot.title = element_text(face = "bold"),
legend.title = element_text(face = "bold", color = "brown",
size = 10)) +
geom_text(aes(x = Var1, y = Var2,
label = round(value, 2)), color = "black",
fontface = "bold", size = 5)
print(p4)
This listing maps correlation-table columns to x, y, and fill, then layers tiles, a color gradient, labels, and rounded coefficient annotations. section 2.5.4
