Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply bold font on specific axis ticks

Tags:

r

ggplot2

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.

like image 272
bretauv Avatar asked May 11 '20 15:05

bretauv


People also ask

How do I make axis ticks bold in Matplotlib?

Matplotlib x-axis label bold Pass the fontweight parameter to the xlabel() function to make the label bold.

How do I make my axis title 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.

How do I make my axis text bold in Python?

The command fontweight='bold' can be used to make a textbox or label in figure bold.


2 Answers

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())

enter image description here

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))

enter image description here

like image 190
eipi10 Avatar answered Sep 27 '22 17:09

eipi10


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()

enter image description here

like image 42
Roman Luštrik Avatar answered Sep 27 '22 15:09

Roman Luštrik