Visualizing Data in R with ggplot2:
Modified ggplot2

Asst. Prof. Dr. Somsak Chanaim

International College of Digital Innovation, CMU

June 24, 2026

theme() function

The theme() function in ggplot2 is used to customize and modify the non-data elements of a plot.

This includes text, background, grid lines, legend, margins, and other visual components.

1 Modify Text Elements (Titles, Labels, Legends)

You can adjust font size, color, alignment, and style for various text elements.

Example: Customizing Text Elements

effect:

  • plot.title → Changes the title font size, color, and centers it (hjust = 0.5).

  • axis.title → Italicizes axis labels and increases size.

  • axis.text → Changes axis text color to red.

  • legend.title → Makes legend title bold.

element_text() function in ggplot

The element_text() function in ggplot2 is used inside the theme() function to customize the appearance of text elements in a plot. It controls font size, color, alignment, bold/italic style, rotation, and more for titles, labels, legends, and other text components.

Syntax of element_text()

element_text(
  family = NULL,     # Font family (e.g., "serif", "sans", "mono")
  face = NULL,       # Font style: "plain", "bold", "italic", "bold.italic"
  color = NULL,     # Text color
  size = NULL,       # Font size
  hjust = NULL,      # Horizontal alignment (0 = left, 0.5 = center, 1 = right)
  vjust = NULL,      # Vertical alignment (0 = bottom, 0.5 = middle, 1 = top)
  angle = NULL,      # Rotate text (in degrees)
  lineheight = NULL  # Line spacing (useful for multi-line text)
)

Examples of element_text() in ggplot2

1 Change Font Size and Color

Modify the title and axis labels.

effect:

  • plot.title = element_text(size = 18, color = "blue") → Increases title size and makes it blue.

  • axis.title = element_text(size = 14, face = "bold") → Increases axis title size and makes it bold.

  • axis.text = element_text(size = 12, color = "red") → Increases axis text size and makes it red.

2 Align and Rotate Text Labels

Effects:

  • hjust = 0.5 → Centers the plot title.

  • angle = 45, hjust = 1 → Rotates x-axis labels by 45 degrees.

3 Change Font Style (Bold, Italic, etc.)

Effects:

  • face = "bold.italic" → Makes the title bold and italic.

  • face = "italic" → Makes axis titles italic.

  • face = "plain" → Keeps axis text normal.

4 Change Font Family

Effects:

  • family = "serif" → Uses a serif font (e.g., Times New Roman).

  • family = "mono" → Uses a monospaced font (e.g., Courier).

Summary: What Can We Do with element_text()?

Feature Parameter Example
Font Size size size = 14
Font Color color color = "red"
Font Style face "plain", "bold", "italic", "bold.italic"
Text Rotation angle angle = 45 (rotate by 45°)
Horizontal Align hjust hjust = 0 (left), 0.5 (center), 1 (right)
Vertical Align vjust vjust = 0 (bottom), 0.5 (middle), 1 (top)
Font Family family "serif", "sans", "mono"

2 Customize Background and Grid Lines

You can modify the plot background, panel background, and grid lines to improve readability.

Example: Changing Background and Grid Style

Effects:

  • panel.background → Changes the plotting area background to light gray.

  • plot.background → Changes the entire plot background to white.

  • panel.grid.major → Changes major grid lines to white.

  • panel.grid.minor → Removes minor grid lines.

3 Adjust Axis Appearance (Ticks, Lines, Text)

You can modify axis lines, ticks, and labels to enhance clarity.

Example: Changing Axis Lines and Ticks

Effects:

  • axis.line → Makes axis lines black and bold.

  • axis.ticks → Changes tick marks to blue and thicker.

  • axis.text.x → Rotates x-axis labels 45 degrees for better readability.

4 Control Legend Position and Style

You can move, resize, or remove the legend.

Example: Moving and Styling the Legend

Effects:

  • legend.position → Moves legend to the bottom.

  • legend.background → Adds gray background and black border to the legend.

  • legend.key → Makes legend keys white.

5 Adjust Margins and Padding

You can modify spacing around the plot to improve layout.

Example: Adding Extra Space Around Plot

Effects:

  • Adds extra space around the plot for better alignment.

Summary: What Can We Do with theme()

Customization Elements to Modify
Text Styling plot.title, axis.title, legend.title, axis.text, legend.text
Background panel.background, plot.background
Grid Lines panel.grid.major, panel.grid.minor
Axis Settings axis.line, axis.ticks, axis.text.x, axis.text.y
Legend legend.position, legend.background, legend.key
Margins plot.margin

theme() allows deep customization of ggplot2 visualizations. You can combine it with predefined themes (theme_minimal(), theme_classic()) for even more control!

annotate() function

The annotate() function in ggplot2 allows you to add custom annotation, such as text, images, and other graphical elements, to a plot.

Unlike geom_text() or geom_label(), which are tied to data, annotate() is used for non-data graphical elements.

Syntax of annotate()

annotate(
  geom,        # Type of annotate (e.g., "text", "rect", "segment")
  xmin, xmax,  # X-axis position (optional)
  ymin, ymax,  # Y-axis position (optional)
  x, y,        # Specific coordinates (optional)
  label,       # Text annotate (for geom="text" or "label")
  fill,        # Background color (for rect or label)
  color,       # Text or border color
  size,        # Text or line size
  alpha        # Transparency (0 = fully transparent, 1 = solid)
)

1 Add Text annotation

Effect: Adds a text label “High Efficiency” at (x = 3, y = 25) in
blue.

2 Add a Rectangular Highlight (annotation for Specific Area)

Effect: Highlights the area (2 ≤ x ≤ 4, 15 ≤ y ≤ 25) in yellow with transparency (30%).

3 Add a Line annotate (Arrow or Segment)

Effect: Draws a red arrow from point (3, 20) to (5, 10).

Summary: What Can annotate() Do?

annotate Type geom Parameter Usage Example
Text annotate "text" Add labels to specific locations
Rectangle "rect" Highlight areas in the plot
Line/Arrow "segment" Draw lines or arrows

Exercise

Exercise 1: Non-Data Graphic Customization via Theme Elements

Modify the structural visual parameters of axis labels. Apply specialized textual elements using the global theme system to modify font faces and discrete programmatic color identities.

Target output

Complete the code

library(ggplot2)
library(gapminder)
gapminder |>
ggplot() +
aes(x = gdpPercap, y = lifeExp) +
geom_point() +
labs(title = "GDP per Capita vs. Life Expectancy",
x = "GDP per Capita",
y = "Life Expectancy") +
theme(
axis.title.x = (color = "red", = "bold"),
axis.title.y = element_text(color = "blue", face = "italic")
)

Exercise 2: Strategic Title Alignment and Typographic Scaling

Modify the global title canvas layout properties. Use localized typography parameters inside the non-data theme layers to govern physical alignment and pixel sizes.

Target output

Complete the code

library(ggplot2)
library(gapminder)
gapminder |>
ggplot() +
aes(x = gdpPercap, y = lifeExp) +
geom_point() +
labs(title = "Population vs. Life Expectancy") +
theme( = element_text(color = "blue", face = "bold", size = 16, = 0))

Exercise 3: Disabling Categorical Legend Displays

Alter the layout configuration of the structural plot canvas by suppressing the default key legends generated during color aesthetic mapping.

Target output

Complete the code

library(ggplot2)
library(gapminder)
gapminder |>
ggplot() +
aes(x = gdpPercap, y = lifeExp, color = continent) +
geom_point() +
theme( = "none")

Exercise 4: Context Canvas Rendering and Grid Modification

Complete the plotting configuration to alter the graphic canvas appearance. Modify structural container attributes using localized polygon rectangles and line style element constructors.

Target output

Complete the code

library(dplyr)
library(ggplot2)
library(gapminder)
gapminder |>
filter(continent == "Asia") |>
ggplot() +
aes(x = year, y = lifeExp, group = country, color = country) +
geom_line() +
theme(
plot.background = (fill = "lightgray"),
panel.grid.major = element_line( = "dashed")
)

Exercise 5: Arbitrary Mathematical Point Annotation

Complete the plotting block to project a free-standing textual annotation layer over targeted coordinate dimensions without parsing variables from the global dataframe map.

Target output

Complete the code

library(ggplot2)
library(gapminder)
gapminder |>
ggplot() +
aes(x = gdpPercap, y = lifeExp) +
geom_point() +
(geom = "text", x = 40000, y = 80, = "Developed Countries", color = "red", size = 5)

Exercise 6: Spatiotemporal Region Highlighting and Alpha Blending

Construct an explicit structural spatial bounding box over the scatter coordinates. Use localized coordinate metrics to frame an analytical window without altering the source data frame.

Target output

Complete the code

library(ggplot2)
library(gapminder)
gapminder |>
ggplot() +
aes(x = gdpPercap, y = lifeExp) +
geom_point() +
annotate(geom = "rect", = 1000, xmax = 5000, ymin = 40, ymax = 60, fill = "yellow", = 0.3)

Exercise 7: Vector Path Ingestion and Arrowhead Annotation

Inject a directional vector path over the continuous data canvas. Complete the configuration to map structural coordinate terminals and append an explicitly defined arrowhead component.

Target output

Complete the code

library(ggplot2)
library(gapminder)
gapminder |>
ggplot() +
aes(x = gdpPercap, y = lifeExp) +
geom_point() +
annotate(geom = "segment", x = 500, = 10000, y = 30, yend = 80, color = "red", = arrow())

Exercise 8: Theme Layer Composition and Selective Grid Suppression

Apply a baseline complete minimal theme to the distribution model, then cascade a localized configuration layer to explicitly drop vertical grid subdivisions.

Target output

Complete the code

library(ggplot2)
library(gapminder)
gapminder |>
ggplot() +
aes(x = continent, y = lifeExp) +
geom_boxplot() +
() +
theme( = element_blank())

Exercise 9: Multivariable Legend Layout Architecture

Reconfigure the layout of the structural plot canvas by altering both the viewport positioning coordinate and the packing direction of the categorical legend elements.

Target output

Complete the code

library(ggplot2)
library(gapminder)
gapminder |>
ggplot() +
aes(x = gdpPercap, y = lifeExp, color = continent) +
geom_point() +
theme( = "bottom", = "horizontal")

Exercise 10: Global Typography and Font Family Heritage

Reconfigure the typography settings across the structural title and axis elements by binding a unified font family typeface to the localized text element constructors.

Target output

Complete the code

library(ggplot2)
library(gapminder)
gapminder |>
ggplot() +
aes(x = pop, y = lifeExp) +
geom_point() +
labs(title = "Population vs. Life Expectancy") +
theme(
plot.title = element_text( = "Times New Roman", face = "bold"),
= element_text(family = "Times New Roman")
)