0
0
R Programmingprogramming~5 mins

Themes and theme customization in R Programming

Choose your learning style9 modes available
Introduction

Themes help you change how your plots look easily. Customizing themes lets you make your charts look just how you want.

You want your chart colors and fonts to match your report style.
You need to make your plot easier to read by changing text size or colors.
You want to create a consistent look for many charts in a project.
You want to highlight certain parts of a plot by changing background or grid lines.
Syntax
R Programming
theme(
  element = value,
  ...
)

# To apply a theme to a ggplot:
ggplot(data) + geom_something() + theme(...)

The theme() function changes parts like text, lines, backgrounds.

You add theme() to your ggplot code to customize the look.

Examples
Change the plot background color and axis text size and color.
R Programming
theme(
  plot.background = element_rect(fill = "lightblue"),
  axis.text = element_text(size = 14, color = "red")
)
Use a simple built-in minimal theme with less clutter.
R Programming
theme_minimal()
Customize grid lines and move the legend below the plot.
R Programming
theme(
  panel.grid.major = element_line(color = "gray", linetype = "dashed"),
  legend.position = "bottom"
)
Sample Program

This program makes a scatter plot of car weight vs. miles per gallon. It changes the background color, grid lines, axis titles and text colors and sizes. It also hides the legend.

R Programming
library(ggplot2)

# Create a simple scatter plot
p <- ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point(color = "blue", size = 3) +
  ggtitle("Car Weight vs. MPG") +
  theme(
    plot.background = element_rect(fill = "#f0f8ff"),
    panel.grid.major = element_line(color = "gray", linetype = "dotted"),
    axis.title = element_text(size = 14, face = "bold", color = "darkgreen"),
    axis.text = element_text(size = 12, color = "purple"),
    legend.position = "none"
  )

print(p)
OutputSuccess
Important Notes

Use element_text() to change fonts, sizes, and colors of text.

Use element_rect() to change backgrounds and borders.

Built-in themes like theme_minimal() or theme_classic() are good starting points.

Summary

Themes control the look of your ggplot charts.

Customize themes with theme() by changing text, colors, grid lines, and more.

Use themes to make your plots clearer and match your style.