The “theme_set” Function in R

  • Package: ggplot2

  • Purpose: To set the default theme for ggplot2 plots for the current session.

  • General Class: Data Visualization

  • Required Argument(s):

    • theme: The theme object to set as the default.

  • Notable Optional Arguments:

    • No notable optional arguments for this function.

  • Example (with Explanation):

  • # Load necessary packages
    library(ggplot2)

    # Plot with the system default theme
    ggplot(mtcars, aes(x = mpg, y = disp)) +
    geom_point() +
    labs(title = "Scatter Plot with Default Theme")

    # Create a custom dark mode theme
    Dark_Mode <- theme_dark() +
    theme(plot.background = element_rect(fill = "black"),
    panel.background = element_rect(fill = "black"),
    axis.text = element_text(color = "white"),
    axis.title = element_text(color = "white"),
    plot.title = element_text(color = "white"))

    # Set the custom theme as the default theme
    theme_set(Dark_Mode)

    # Plot with the new dark default theme, added color = "white"
    ggplot(mtcars, aes(x = mpg, y = disp)) +
    geom_point(color = "white") +
    labs(title = "Scatter Plot with Dark Theme")

    # Reset the default theme back to minimal
    theme_set(theme_minimal())

    # Plot with the default theme
    ggplot(mtcars, aes(x = mpg, y = disp)) +
    geom_point() +
    labs(title = "Scatter Plot with Default Theme")

  • In this example, the theme_set function is used to set a custom theme as the default for the current session. The custom theme is applied to a new scatter plot, and then the theme is reset to the default for the session. This function allows you to easily change the default theme for all subsequent plots in a session.

Previous
Previous

The “theme_classic” Function in R

Next
Next

The “theme_void” Function in R