在特定的轴刻度上应用粗体 [英] Apply bold font on specific axis ticks
问题描述
这是情节:
library(ggplot2)
library(tibble)
ggplot(head(mtcars) %>% rownames_to_column("cars"),
aes(x = reorder(cars, - drat),
y = drat)) +
geom_col() +
coord_flip()
如何在特定的汽车名称上(例如仅在"Hornet 4 Drive"和"Datsun 710"上)应用粗体?
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.
推荐答案
ggtext
允许您将markdown和html标签用于轴标签和其他文本.因此,我们可以创建一个函数传递给scale_y_discrete
的labels
参数(如@RomanLuštrik在其注释中建议的那样),通过该函数我们可以选择要突出显示的标签,颜色和字体系列:
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屋!