Home > Blockchain >  Color specific axis tick label in ggplot
Color specific axis tick label in ggplot

Time:11-15

I would like to color a specific axis tick label when calling in a custom function. For example, take this graph:

library(ggplot2)
ggplot(mtcars, aes(x = as.factor(cyl)))  
  geom_bar()

Created on 2022-11-15 with reprex v2.0.2

I would like to color the xaxis tick label 6 with "red". You can color the axis.text.x with element_text in your theme like this:

library(ggplot2)
ggplot(mtcars, aes(x = as.factor(cyl)))  
  geom_bar()  
  theme(axis.text.x = element_text(colour = c("black", "red", 'black')))

Created on 2022-11-15 with reprex v2.0.2

But of course, this isn't really automatic and smooth. Here is a starting point for a custom function:

color_axis_tick_label <- function(df, xaxis, xaxistick) {
  ggplot(df, aes(x = as.factor({{xaxis}})))  
    geom_bar()
} 

Does anyone know if it is possible to do this in a more automatic way?

CodePudding user response:

One option would be to use ggtext::element_markdown and a custom function for the labels argument of the scale:

library(ggplot2)
library(ggtext)

color_axis_tick_label <- function(df, xaxis, xaxistick) {
  ggplot(df, aes(x = as.factor({{ xaxis }})))  
    scale_x_discrete(
      labels = ~ ifelse(.x %in% xaxistick,
        paste0("<span style='color: red'>", .x, "</span>"), .x
      )
    )  
    geom_bar()  
    theme(axis.text.x = ggtext::element_markdown())
}

color_axis_tick_label(mtcars, cyl, 6)

  • Related