Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot conditionally make axis labels bold in ggplot

Tags:

r

ggplot2

ggtext

I am trying to make select axis labels bold, based on a conditional from a different column. In the code below, if Signif equals 1, then the Predictor axis text should be bold. In addition, the segments should appear in the order of Values increasing value.

However, this code is not changing any of the the axis texts to bold.

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())

enter image description here

If instead I use element_text() in the last line, and skip the mutate to markdown step above:

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"))) 

It bolds the 2nd and 4th axis label, which corresponds to the Signif equals 1 in the original df.

enter image description here

How can I get the correct axis text labels to appear in bold?

like image 317
Adam_G Avatar asked Aug 29 '26 23:08

Adam_G


1 Answers

I would’ve expected your code to work honestly, but you can use <b> instead of <span style...>:

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

df <- df %>% 
  mutate(Predictor = ifelse(Signif==1,
                            glue("<b>{Predictor}</b>"),
                            Predictor))

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())

like image 140
zephryl Avatar answered Aug 31 '26 14:08

zephryl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!