Recently, I have been trying to add some text annotations to ggplot2 graphs using annotate()
function. Here is a basic example;
p <- ggplot(mtcars, aes(x = wt, y = mpg)) geom_point()
p annotate("text", x = 4, y = 25, label = "Some text")
The problem I am facing in using annotate()
function is related to its customization. In other words, when I try to customize the text I want to add on the graph using basic CSS, Some text
, such as changing the color and font size of text
word, it does not allow me to do so. Therefore, I want to inquire how I can customize text annotations I want to put on the ggplot2 graphs? Thank you for your attention beforehand.
CodePudding user response:
If you look at ?geom_text
you will see the aesthetics that can be applied to a text layer. The main ones are demonstrated below:
p annotate("text", x = 4, y = 25, label = "Some text",
color = "red",
size = 15,
family = "serif",
fontface = "bold")
If you are desperate to use css instead of passing parameters to annotate
, you could try loading the ggtext
package and using annotation
with geom = "richtext"
instead of geom = "text"
. It only covers a small subset of css (essentially just those properties shown above and one or two others)
library(ggtext)
p annotate(geom = 'richtext', x = 4, y = 25, color = NA, fill = NA,
label='<span style="color:red; font-size:15mm; font-family:serif;">
<b>Some text</b></span>')