这是一个情节:
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”上)?
我更喜欢一个非常“通用”的答案,即一个可以轻松应用特定颜色或其他字体系列而不是粗体字体的答案。
ggtext
允许您使用 markdown 和 html 标签作为轴标签和其他文本。所以我们可以创建一个函数来传递给labels
的论证scale_y_discrete
(正如 @RomanLuštrik 在他们的评论中建议的那样),通过它我们可以选择要突出显示的标签、颜色和字体系列:
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))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)