无法有条件地使 ggplot 中的轴标签变为粗体

Ada*_*m_G 2 r ggplot2 ggtext

我正在尝试根据不同列中的条件将选择轴标签设为粗体。在下面的代码中,如果Signif等于 1,则Predictor轴文本应为粗体。此外,各段应按Value值递增的顺序出现。

但是,此代码不会将任何轴文本更改为粗体。

library(tidyverse)
library(ggtext)
library(glue)

df <- tibble(Predictor = c("Blue","Red","Green","Yellow"),
             Value = c(1,3,2,4),
             Signif = c(0,1,0,1))

df <- df %>% mutate(Predictor = ifelse(Signif==1,
                                 glue("<span style = 'font-weight:bold'>{Predictor}</span>"),
                                 glue("<span style = 'font-weight:plain'>{Predictor}</span>"))
)

df %>% 
  arrange(desc(Value)) %>% 
  mutate(Predictor=factor(Predictor, 
                          levels=df$Predictor[order(df$Value)])) %>%
  ggplot(aes(x=Predictor, y=Value)) +
  geom_segment(aes(xend=Predictor, yend=0)) +
  theme(axis.text.x = element_markdown())
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

如果我在最后一行使用element_text(),并跳过mutate上面的降价步骤:

df %>% 
  arrange(desc(Value)) %>% 
  mutate(Predictor=factor(Predictor, 
                          levels=df$Predictor[order(df$Value)])) %>%
  ggplot(aes(x=Predictor, y=Value)) +
  geom_segment(aes(xend=Predictor, yend=0)) +
  theme(axis.text.x = element_text(face = if_else(df$Signif==1, "bold", "plain"))) 
Run Code Online (Sandbox Code Playgroud)

它将第二和第四轴标签加粗,对应于Signif原始 df 中的等于 1。

在此输入图像描述

如何使正确的轴文本标签以粗体显示?

zep*_*ryl 5

我\xe2\x80\x99ve期望你的代码能够诚实地工作,但你可以使用<b>而不是<span style...>

\n
library(tidyverse)\nlibrary(ggtext)\nlibrary(glue)\n\ndf <- df %>% \n  mutate(Predictor = ifelse(Signif==1,\n                            glue("<b>{Predictor}</b>"),\n                            Predictor))\n\ndf %>% \n  arrange(desc(Value)) %>% \n  mutate(Predictor=factor(Predictor, \n                          levels=df$Predictor[order(df$Value)])) %>%\n  ggplot(aes(x=Predictor, y=Value)) +\n  geom_segment(aes(xend=Predictor, yend=0)) +\n  theme(axis.text.x = element_markdown())\n
Run Code Online (Sandbox Code Playgroud)\n

\n