mmiller524
mmiller524

Reputation: 27

ggplot2: Conditional formatting of x axis label in facet_grid

First post so please forgive any transgressions.

The data (russ_defensive) looks something like this

russ_defensive dataframe

And this code is meant to create a facet_grid of stacked bars conditionally filled by capitalisation and with axis.text.x colour set to red or black based on whether the industry is defensive or not

library(dplyr)
library(ggplot2)

chart_foo <- ggplot(data = russ_defensive, aes(x = industry)) + 
facet_grid(~ sector, space = "free", scales="free") +  
geom_bar(stat="count") +  aes(fill = capitalisation) +
theme(axis.text.x = element_text(angle = 90, color = ifelse(russ_defensive$defensive_industries == "N", "red", "black")))

Around half of the industries are non-defensive (so russ_defensive$defensive_industries is "N") however this code only turns one of the labels red (see here) and gives the following error:

Warning message:
Vectorized input to `element_text()` is not officially supported.
Results may be unexpected or may change in future versions of ggplot2. 

Is there a simple fix to this/ alternate method to conditionally formatting labels based on a column of the dataset?

Thanks for any help, if a reproducible dataset would be useful please let me know.

Upvotes: 0

Views: 1145

Answers (1)

teunbrand
teunbrand

Reputation: 38063

Well, as the warning tells you it is not recommended to choose the axis text colours by using vectorised theme input (although many people try nonetheless). I believe this was also one of the motivations behind the ggtext package, in which you can use markdown to stylise your text. Below, you'll find an example with a standard dataset, I hope it translates well to yours. We just conditionally apply colouring to some of the x-axis categories.

library(ggplot2)
library(ggtext)
#> Warning: package 'ggtext' was built under R version 4.0.3

df <- transform(mtcars, car = rownames(mtcars))[1:10,]

red_cars <- sample(df$car, 5)

df$car <- ifelse(
  df$car %in% red_cars,
  paste0("<span style='color:#FF0000'>", df$car, "</span>"),
  df$car
)


ggplot(df, aes(car, mpg)) +
  geom_col() +
  theme(axis.text.x = element_markdown(angle = 90))

Created on 2021-02-03 by the reprex package (v1.0.0)

For more examples, see https://github.com/wilkelab/ggtext#markdown-in-theme-elements

Upvotes: 2

Related Questions