在特定轴刻度上应用粗体字体

bre*_*auv 8 r ggplot2

这是一个情节:

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”上)?

我更喜欢一个非常“通用”的答案,即一个可以轻松应用特定颜色或其他字体系列而不是粗体的答案。

eip*_*i10 8

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)

在此处输入图片说明

  • 在当前版本的 ggplot2 中,不需要指定`coord_flip`。如果将离散变量映射到 y 轴,ggplot 会自动将绘图渲染为水平图。 (2认同)

Rom*_*rik 7

似乎有一种更简单的方法可以解决这个问题(无需制作自己的贴标机)。只需在 中指定标签的具体面即可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)

在此输入图像描述

  • 它可以工作,但会产生警告:“警告消息:‘element_text()’的矢量化输入不受官方支持”。结果可能会出乎意料,或者可能会在 ggplot2 的未来版本中发生变化。``你知道是否可以修复它吗? (2认同)