使用 reorder_within 后在轴标签中加粗项目

bold an item in axis label after using reorder_within

我正在使用 R 中 tidytext 包中的 reorder_within() 函数绘制不同频率的图。一个类似的例子来自 here.

library(tidytext)

top_names %>%
    group_by(decade) %>%
    top_n(15) %>%
    ungroup %>%
    mutate(decade = as.factor(decade),
           name = reorder_within(name, n, decade)) %>%
    ggplot(aes(name, n, fill = decade)) +
    geom_col(show.legend = FALSE) +
    facet_wrap(~decade, scales = "free_y") +
    coord_flip() +
    scale_x_reordered() +
    scale_y_continuous(expand = c(0,0)) +
    labs(y = "Number of babies per decade",
         x = NULL,
         title = "What were the most common baby names in each decade?",
         subtitle = "Via US Social Security Administration")

输出图像为:

我将如何着手在每个方面加粗单个项目?例如,如果我想在每个方面的轴标签上加粗名字 David,我该怎么做?

与@tamtam 链接的答案中的解决方案相比,这是一个需要最少开销的解决方案:您可以使用 ggtext::element_markdown 将 ggplot 中的任何文本解释为降价。只需添加 axis.text.y = ggtext::element_markdown(),所有形式为 "**Name**" 的变量名称都以粗体显示:

library(ggplot2)
library(dplyr)
library(tidytext)

test_data <- data.frame(
  decade = rep(c("1950", "1960", "1970", "1980"), each = 3),
  name = rep(c("Max", "**David**", "Susan"), 4),
  n = c(2, 1, 4, 5, 3, 1, 5, 7, 10, 4, 5, 3)
)


test_data %>%
  group_by(decade) %>%
  ungroup %>%
  mutate(decade = as.factor(decade),
         name = reorder_within(name, n, decade)) %>%
  ggplot(aes(name, n, fill = decade)) +
  geom_col(show.legend = FALSE) +
  facet_wrap(~decade, scales = "free_y") +
  coord_flip() +
  scale_x_reordered() +
  scale_y_continuous(expand = c(0,0)) +
  labs(y = "Number of babies per decade",
       x = NULL,
       title = "What were the most common baby names in each decade?",
       subtitle = "Via US Social Security Administration") +
  theme(axis.text.y = ggtext::element_markdown())

reprex package (v0.3.0)

于 2020-09-22 创建

除了@starja 的优秀示例之外,您还可以尝试使用 glue 包在名称上构建条件,然后使用函数进行排序。关键是将标签格式设置为 ggtext 中的 element_markdown()。这里的代码使用了整个数据:

library(tidyverse)
library(ggtext)
library(glue)
library(babynames)
#Data
top_names <- babynames %>%
  filter(year >= 1950,
         year < 1990) %>%
  mutate(decade = (year %/% 10) * 10) %>%
  group_by(decade) %>%
  count(name, wt = n, sort = TRUE) %>%
  ungroup
#Plot
top_names %>%
  group_by(decade) %>%
  top_n(15) %>%
  ungroup %>%
  mutate(name=ifelse(name=='David',glue("**{name}**"),name)) %>%
  mutate(decade = as.factor(decade),
         name = reorder_within(name, n, decade)) %>%
  ggplot(aes(name, n, fill = decade)) +
  geom_col(show.legend = FALSE) +
  facet_wrap(~decade, scales = "free_y") +
  coord_flip() +
  scale_x_reordered() +
  scale_y_continuous(expand = c(0,0)) +
  labs(y = "Number of babies per decade",
       x = NULL,
       title = "What were the most common baby names in each decade?",
       subtitle = "Via US Social Security Administration")+
  theme(axis.text.y = element_markdown())

输出: