Here's a plot:
library(ggplot2)
library(tibble)
ggplot(head(mtcars) %>% rownames_to_column("cars"),
aes(x = reorder(cars, - drat),
y = drat)) +
geom_col() +
coord_flip()
How can I apply bold font on specific car names (for example just on "Hornet 4 Drive" and "Datsun 710")?
I would prefer a quite "general" answer, i.e an answer that makes it easy to apply a particular color or another font family instead of bold font.
Matplotlib x-axis label bold Pass the fontweight parameter to the xlabel() function to make the label bold.
Make Axis Title Text Bold Font with element_text() To make both x and y-axis's title text in bold font, we will use axis. title argument to theme() function with element_text(face=”bold”). Note now both x and y axis's title text are in bold font.
The command fontweight='bold' can be used to make a textbox or label in figure bold.
ggtext
allows you to use markdown and html tags for axis labels and other text. So we can create a function to pass to the labels
argument of scale_y_discrete
(as @RomanLuštrik suggested in their comment), through which we can select the labels to highlight, the color, and the font family:
library(tidyverse)
library(ggtext)
library(glue)
highlight = function(x, pat, color="black", family="") {
ifelse(grepl(pat, x), glue("<b style='font-family:{family}; color:{color}'>{x}</b>"), x)
}
head(mtcars) %>% rownames_to_column("cars") %>%
ggplot(aes(y = reorder(cars, - drat),
x = drat)) +
geom_col() +
scale_y_discrete(labels= function(x) highlight(x, "Datsun 710|Hornet 4", "red")) +
theme(axis.text.y=element_markdown())
iris %>%
ggplot(aes(Species, Petal.Width)) +
geom_point() +
scale_x_discrete(labels=function(x) highlight(x, "setosa", "purple", "Copperplate")) +
theme(axis.text.x=element_markdown(size=15))
It would seem there's an easier way to approach this (no need to make your own labeller). Just specify specific face of the label in theme(axis.text.y)
. Notice that I had to define the x axis values as a factor to make order of labels predictable.
library(ggplot2)
mtcars$cars <- as.factor(rownames(mtcars))
bold.cars <- c("Merc 280", "Fiat 128")
bold.labels <- ifelse(levels(mtcars$cars) %in% bold.cars, yes = "bold", no = "plain")
ggplot(mtcars, aes(x = cars, y = drat)) +
theme(axis.text.y = element_text(face = bold.labels)) +
geom_col() +
coord_flip()
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