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 Value
s 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())
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.
How can I get the correct axis text labels to appear in bold?
CodePudding user response:
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())
CodePudding user response:
The issue is that ggtext
currently supports only a limited set of CSS properties. From the