tezvyn:

ggplot2: Building Graphics with a Grammar

AI-drafted, machine-checkedSource: ggplot2.tidyverse.orgintermediate

ggplot2 treats plots like sentences. You declare components—data, aesthetics (x/y axes, color), and geoms (points, bars)—and it assembles the visual. It's essential for data exploration in R, letting you iterate by swapping layers.

WHY IT EXISTS: To provide a systematic, reproducible way to create graphics. Instead of a series of imperative commands like "draw a point here, draw a line there," it separates the "what" (the data and its mapping) from the "how" (the rendering details), making complex plots more manageable and logical.

THE MENTAL MODEL: Think of building a plot like constructing a sentence. You have nouns (the data), verbs (the geometric shapes, or 'geoms'), and adjectives/adverbs (the aesthetic mappings that describe how data maps to visual properties like color, size, or position). You combine these grammatical components layer by layer to build a complete, coherent visual statement.

HOW IT WORKS: Every plot starts with the ggplot() function, which you supply with data and aesthetic mappings via aes(). The aes() function specifies how variables in your data map to visual properties like x/y position, color, or shape. After setting up this base, you add one or more layers using the + operator. Each layer is a 'geom' function, like geom_point() for scatter plots or geom_bar() for bar charts, which defines how the data is graphically represented. You can continue adding layers, scales (scale_color_brewer()), or facets (facet_wrap()) to refine the plot.

WHEN TO USE IT: Use ggplot2 for nearly all static data visualization tasks in R. It excels at exploratory data analysis, where you can quickly swap out geoms or aesthetic mappings to view data from different angles. It is also the standard for creating complex, multi-layered, publication-quality graphics due to its logical structure and extensive customization.

WHEN NOT TO USE IT: ggplot2 is for static, 2D graphics. For highly interactive visualizations that respond to user input in a browser, libraries like plotly or shiny are better suited. For extremely simple, quick-and-dirty plots, base R's plot() function can sometimes be faster, though ggplot2's consistency is often worth the initial setup.

ONE CANONICAL EXAMPLE: To create a scatter plot of highway MPG vs. engine displacement from the mpg dataset, coloring points by vehicle class, the code is declarative: ggplot(data = mpg, aes(x = displ, y = hwy, color = class)) + geom_point() This tells ggplot2: use the mpg dataset, map displ to the x-axis, hwy to the y-axis, and class to color, then represent this with a layer of points.

Read the original → ggplot2.tidyverse.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.