这是一个情节:
library(ggplot2)
library(tibble)
ggplot(head(mtcars) %>% rownames_to_column("cars"),
aes(x = reorder(cars, - drat),
y = drat)) +
geom_col() +
coord_flip()
Run Code Online (Sandbox Code Playgroud)
如何在特定汽车名称上应用粗体(例如仅在“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())
Run Code Online (Sandbox Code Playgroud)
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))
Run Code Online (Sandbox Code Playgroud)
似乎有一种更简单的方法可以解决这个问题(无需制作自己的贴标机)。只需在 中指定标签的具体面即可theme(axis.text.y)。请注意,我必须将 x 轴值定义为一个因素,以使标签的顺序可预测。
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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2725 次 |
| 最近记录: |