labs()

The labs() function is part of the ggplot2 package.

Example 1: Customizing Plot Titles

The labs() function allows you to modify plot titles. Let’s start with a basic example:
library(ggplot2)

# Create a simple scatter plot
data <- data.frame(x = 1:10, y = 1:10)
ggplot(data, aes(x, y)) +
geom_point() +
labs(
title = “Scatter Plot of X and Y”,
x = “X-axis Label”,
y = “Y-axis Label”
)

#In this example, we use labs() to set the plot title and axis labels. The resulting plot will have a customized title and labels.

Add a Subtitle and Caption to a Chart

Adding a subtitle allows us to add more contect to the chart


ggplot(data, aes(x, y)) +
geom_point() +
labs(
title = "Scatter Plot of X and Y",
subtitle = "A simple example with custom labels",
caption = "This is a caption Created by Floyd",
x = "X-axis Label",
y = "Y-axis Label"
)

Changing Text Properties

ggplot(data, aes(x, y)) +
geom_point() +
labs(
title = expression(bold("Scatter Plot of X and Y")),
x = "X-axis Label",
y = expression(italic("Y-axis Label"))
)

 

Themes May be added to Visualizations

Themes may be added to make your presentation more cohesive

ggplot(data, aes(x, y)) +
geom_point() +
labs(
title = "Scatter Plot of X and Y",
x = "X-axis Label",
y = "Y-axis Label"
) +
theme_dark()

 

Rotating Axis Labels

ggplot(data, aes(x, y)) +
geom_point() +
labs(
title = "Scatter Plot of X and Y",
x = "X-axis Label",
y = "Y-axis Label"
) +
theme(axis.text.x = element_text(angle = 45, hjust = 1))

Annotate Charts

The annotate() function is used to write on the chart.
ggplot(data, aes(x, y)) +
geom_point() +
labs(
title = "Scatter Plot of X and Y",
x = "X-axis Label",
y = "Y-axis Label"
) +
annotate("text")
theme(axis.text.x = element_text(angle = 45, hjust = 1))

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top