Visualizing Data in R with ggplot2:
Modified ggplot2

Somsak Chanaim

International College of Digital Innovation, CMU

April 8, 2025

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: Customize Axis Labels with theme()

Create a scatter plot of GDP per capita vs. life expectancy.

Use theme() to:

  • Change the x-axis label to bold red text.

  • Change the y-axis label to blue italic text.

solution

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 = element_text(color = "red", face = "bold"),
    axis.title.y = element_text(color = "blue", face = "italic")
  )

Exercise 2: Modify the Plot Title Using element_text()

Generate a scatter plot of population vs. life expectancy.

Use theme() and element_text() to:

  • Set the plot title to blue, bold, and size 16.

  • Align the title to the left.

solution

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

Exercise 3: Remove the Legend

Create a colored scatter plot of GDP per capita vs. life expectancy, where the color represents the continent.

Use theme() to remove the legend.

solution

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

Exercise 4: Change Background Color

Create a line plot of life expectancy over time for Asia.

Use theme() to:

  • Change the plot background to light gray.

  • Change the panel grid lines to dashed.

solution

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

Exercise 5: Add a Text Annotation Using annotate()

Create a scatter plot of GDP per capita vs. life expectancy.

Use annotate() to:

  • Add a text label at (x = 40000, y = 80) saying “Developed Countries” in red.

solution

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

Exercise 6: Highlight a Specific Region with annotate(“rect”)

Create a scatter plot of GDP per capita vs. life expectancy.

Use annotate("rect") to:

  • Highlight a rectangular area where GDP per capita is between 1000 and 5000 and life expectancy is between 40 and 60 in yellow (with transparency).

solution

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

Exercise 7: Use annotate(“segment”) to Draw an Arrow

Create a scatter plot of GDP per capita vs. life expectancy.

Use annotate("segment") to:

  • Draw a red arrow from (x = 500, y = 30) to (x = 10000, y = 80).

solution

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

Exercise 8: Use theme_bw() and Modify Grid Lines

Create a boxplot of life expectancy by continent.

Use:

  • theme_bw() for a clean look.

  • Use theme() to remove the vertical grid lines.

solution

gapminder |> 
ggplot() +
  aes(x = continent, y = lifeExp) +
  geom_boxplot() +
  theme_bw() +
  theme(panel.grid.major.x = element_blank())

Exercise 9: Change Legend Position

Create a scatter plot of GDP per capita vs. life expectancy, coloring by continent.

Use theme() to:

  • Move the legend to the bottom and set it to horizontal.

solution

gapminder |> 
ggplot() +
  aes(x = gdpPercap, y = lifeExp, color = continent) +
  geom_point() +
  theme(legend.position = "bottom", 
       legend.direction = "horizontal")

Exercise 10: Change Font Family Using theme()

Create a scatter plot of population vs. life expectancy.

Use theme() to:

  • Set the title and axis labels to use the “Times New Roman” font.

solution

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