Is there an elegant way in ggplot2
to make geom_text
/geom_label
inherit theme
specifications like a base_family
?
Or asked the other way round: Can I specify a theme
that also applies to geom_text
/geom_label
?
Example:
I want text/labels
to look exactly like the axis.text
as specified in the theme
...
Obviously I could add the specifications manually as optional arguments to geom_text
, but I want it to inherit the specifications "automatically"...
library("ggplot2")
ggplot(mtcars, aes(x = mpg,
y = hp,
label = row.names(mtcars))) +
geom_point() +
geom_text() +
theme_minimal(base_family = "Courier")
Addition: A solution that works with ggrepel::geom_text_repel/geom_label_repel
as well would be perfect...
You can
Firstly, depending on the system you will need to check which fonts are available. As I am running on Windows I am using the following:
install.packages("extrafont")
library(extrafont)
windowsFonts() # check which fonts are available
The theme_set
function lets you specify the overall themes for ggplot. So therefore theme_set(theme_minimal(base_family = "Times New Roman"))
lets you define the fonts for the plot.
To make the labels inherit this text, there are two things we need to use:
update_geom_defaults
lets you update the geometry object styling for future plots in ggplot: http://ggplot2.tidyverse.org/reference/update_defaults.html
theme_get()$text$family
extracts the font of the current global ggplot theme.By combining these two, the label styles can be updated as follows:
# Change the settings
update_geom_defaults("text", list(colour = "grey20", family = theme_get()$text$family))
update_geom_defaults("text_repel", list(colour = "grey20", family = theme_get()$text$family))
theme_set(theme_minimal(base_family = "Times New Roman"))
# Change the settings
update_geom_defaults("text", list(colour = "grey20", family = theme_get()$text$family))
# Basic Plot
ggplot(mtcars, aes(x = mpg,
y = hp,
label = row.names(mtcars))) +
geom_point() +
geom_text()
# works with ggrepel
update_geom_defaults("text_repel", list(colour = "grey20", family = theme_get()$text$family))
library(ggrepel)
ggplot(mtcars, aes(x = mpg,
y = hp,
label = row.names(mtcars))) +
geom_point() +
geom_text_repel()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With