Customizing Themes and Saving Plots

Customizing Themes and Saving Plots

Welcome back! In the last lesson, you created bar plots and histograms to summarize both categorical and continuous data. This time, you’ll take your visualizations to the next level by learning how to customize themes and save your plots. Customizing themes not only makes your plots more attractive but also highlights the important aspects of your data.

What You'll Learn

In this unit, you’ll learn how to enhance your plots with custom themes and save them to files. We’ll start with a scatter plot of the iris dataset to review what you already know. Then, you’ll discover how you can add personalization to your plots by changing the text size, and font, and even save your work for future use.

By the end of this lesson, you'll be able to generate a scatter plot like the one shown below:

Here's a sneak peek at the code you'll be working with:

R
# Load the built-in iris dataset
data(iris)

# Create the scatter plot and customize the theme
p <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  theme_light() +
  labs(title = "Sepal Length vs Sepal Width",
       x = "Sepal Length",
       y = "Sepal Width") +
  theme(
    plot.title = element_text(size = 14, face = "bold"),
    axis.title.x = element_text(size = 12, face = "italic"),
    axis.title.y = element_text(size = 12, face = "bold.italic")
  )

# Save the customized plot to a file
ggsave("scatter_plot.png", plot = p, width = 7, height = 7)

Step-by-Step Breakdown

Load built-in dataset

Let's start by loading the iris dataset.

R
data(iris)

Creating the Scatter Plot

Let's start creating the scatter plot by using the iris dataset. The ggplot function initializes the plot and aes sets the aesthetic mappings, defining the x and y axes and the color to differentiate species. We add geom_point() to plot the data points.

R
p <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point()
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal