在 r 中的 ggplot2 中将分配给 y 轴文本的字符串的第一行加粗
Bold the first line of strings that are assigned to y-axis text in ggplot2 in r
以 followinf 数据帧为例
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
看起来像这样:
> 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
现在,如果我创建此数据的简单散点图:
ggplot(DF2, aes(x = X, y = Y)) + geom_point()
如何将 y 轴文本的第一行设为粗体?所以我希望 this is the first line thats bold 1(2,3)
加粗,this is the second line thats plain A(B,C)
保持简洁。
ggtext
包允许将轴文本格式化为 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())
由 reprex package (v2.0.0)
于 2022-04-27 创建
以 followinf 数据帧为例
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
看起来像这样:
> 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
现在,如果我创建此数据的简单散点图:
ggplot(DF2, aes(x = X, y = Y)) + geom_point()
如何将 y 轴文本的第一行设为粗体?所以我希望 this is the first line thats bold 1(2,3)
加粗,this is the second line thats plain A(B,C)
保持简洁。
ggtext
包允许将轴文本格式化为 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())
由 reprex package (v2.0.0)
于 2022-04-27 创建