Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
The post How to Add a caption to ggplot2 Plots in R? appeared first on Data Science Tutorials
How to Add a caption to ggplot2 Plots in R?, the graphs in ggplot2 can have captions added using one of the methods listed below.
With the following data frame in R, the following examples demonstrate how to use each technique in practice.
A Side-by-Side Boxplot in R: How to Do It – Data Science Tutorials
Let’s create a data frame
df <- data.frame(x=c(1, 2, 2, 3, 4, 5, 6, 7, 8), y=c(23, 36, 39, 31, 32, 33, 36, 39, 23))
Now we can view the data frame
df x y 1 1 23 2 2 36 3 2 39 4 3 31 5 4 32 6 5 33 7 6 36 8 7 39 9 8 23
Example 1: Add Caption in Default Location
The code that follows demonstrates how to make a scatter plot in gglot2 and insert a caption in the plot’s default place (the bottom right corner):
library(ggplot2)
Let’s create a scatter plot with a caption in the bottom left corner
ggplot(df, aes(x=x, y=y)) + geom_point(size=3) + labs(caption = "Based on 2022 Asia Cup Data")
A caption has been added to the lower right corner of the image outside the plot, as you can see.
Change ggplot2 Theme Color in R- Data Science Tutorials
Example 2: Add Caption in Custom Location
The code below demonstrates how to make a scatter plot in gglot2 and add a caption to the plot’s bottom left corner.
library(ggplot2)
Now we can create a scatter plot with a caption in the default location
ggplot(df, aes(x=x, y=y)) + geom_point(size=3) + labs(caption = "Based on 2022 Asia Cup Data") + theme(plot.caption = element_text(hjust=0))
The lower left corner of the image outside the plot now has a caption.
Note: You can use hjust=0.5 to center the caption outside of the plot in the bottom right corner.
How to Get a Job as a Data Engineer? – Data Science Tutorials
Example 3: Customize Text & Add Caption
The gglot2 code below demonstrates how to make a scatter plot and add a caption with a personalized color, size, and style.
library(ggplot2)
Let’s try to create a scatter plot with a caption in the default location
ggplot(df, aes(x=x, y=y)) + geom_point(size=3) + labs(caption = "Based on 2022 Asia Cup Data") + theme(plot.caption = element_text(size=16, color="red", face="italic"))
A caption with a unique color, text size, and style has been added to the bottom right corner of the image outside the plot.
Top 10 online data science programs – Data Science Tutorials
The post How to Add a caption to ggplot2 Plots in R? appeared first on Data Science Tutorials
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.