This post explains how to create plots with
texts or to combine chart and text in your ggplot2
plots using the geomtextpath package.
This post showcases the
key features of geomtextpath
and provides
a set of graph examples using the package.
{geomtextpath}
The geomtextpath
package in R is an extension of the ggplot2
package, designed to simplify the process of adding text in
charts, especially when you need the text to follow a
curved path.
To get started with geomtextpath
, you can install it
directly from CRAN using the install.packages
function:
The geomtextpath
package needs the x and y coordinates,
the label, and you’re good to go!
To keep in mind: in function names, you can change the
text
to label
(and vice versa) to choose
whether the text should be framed or not.
Here’s a basic example:
library(ggplot2)
library(geomtextpath)
t = seq(5, -1, length.out = 1000) * pi
spiral = data.frame(x = sin(t) * 1:1000,
y = cos(t) * 1:1000,
text = paste("From elegant bar charts to mesmerizing scatterplots,",
"crafting stunning visualizations in R is powerful,",
"you can bring your data to life, revealing insights.")
)
ggplot(spiral, aes(x, y, label = text)) +
geom_textpath(size = 5, vjust = 1, text_only = TRUE)
You can have the text in a box thanks to the
geom_labelpath()
function.
Example:
The geom_textdensity()
can be used to plot group name
directly on the curve of a density chart. You can adjust the
position of the text with the vjust
and
hjust
arguments (numerical value or
“xmid”/“ymax”/“auto”).
Example with the iris dataset:
You can add trend lines with the group label on top with the
geom_labelsmooth()
function
Example:
You can add reference lines with your own label thanks to the
geom_texthline()
, geom_textvline()
and
geom_textabline()
functions.
Example:
data(mtcars)
ggplot(mtcars, aes(mpg, disp)) +
geom_point() +
geom_texthline(yintercept = 200, label = "displacement threshold",
hjust = 0.8, color = "red") +
geom_textvline(xintercept = 20, label = "consumption threshold", hjust = 0.8,
linetype = 2, vjust = 1.3, color = "blue") +
geom_textabline(slope = 15, intercept = -100, label = "partition line",
color = "green3", hjust = 0.6, vjust = -0.2)
👋 After crafting hundreds of R charts over 12 years, I've distilled my top 10 tips and tricks. Receive them via email! One insight per day for the next 10 days! 🔥