'Bold the first line of strings that are assigned to y-axis text in ggplot2 in r
Considering the followinf dataframes as an example
DF1 <- data.frame(A = c(1, 2, 3), B = c("a", "b", "c"))
DF2 <- data.frame(Y = paste0("this is the first line thats bold ", DF1$A, "\n",
"this is the second line thats plain ", DF1$B),
X = structure(c(18903, 18965, 19081), class = "Date"))
DF2 looks like this:
> DF2
Y X
1 this is the first line thats bold 1\nthis is the second line thats plain a 2021-10-03
2 this is the first line thats bold 2\nthis is the second line thats plain b 2021-12-04
3 this is the first line thats bold 3\nthis is the second line thats plain c 2022-03-30
Now if I create a simple scatter plot of this data:
ggplot(DF2, aes(x = X, y = Y)) + geom_point()
How can I make the first line of the y-axis text bold? so I want the this is the first line thats bold 1(2,3) be bold and the this is the second line thats plain A(B,C) to remain plain.
Solution 1:[1]
ggtext package allows to format axis text as Markdown:
library(ggtext)
library(tidyverse)
DF1 <- data.frame(A = c(1, 2, 3), B = c("a", "b", "c"))
DF2 <- data.frame(
Y = paste0(
"this is the first line thats bold ", DF1$A, "\n",
"this is the second line thats plain ", DF1$B
),
X = structure(c(18903, 18965, 19081), class = "Date")
)
DF2 %>%
mutate(Y = Y %>% str_replace("^", "**") %>% str_replace("\n", "**\n\n")) %>%
ggplot(aes(x = X, y = Y)) +
geom_point() +
theme(axis.text.y = element_markdown())

Created on 2022-04-27 by the reprex package (v2.0.0)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | danlooo |

