I am trying to color a specific label on the y-axis by using: theme(axis.text.y = element_markdown(color = ...))
and it works perfectly fine. However, when I also want to prevent myself from potential label overlapping on this very same axis by using :
scale_y_discrete(guide = guide_axis(check.overlap = T))
, then, the coulored label is changed. Here is a small example showing this issue.
As anyone already faced this issue? Do you have a solution for it ? Or another way of doing it?
library(ggplot2)
library(ggtext)
N = 10
df = data.frame(parameters = paste("paramters", seq(N), sep = "_"),
color = rep("black", N))
df$parameters = factor(df$parameters, levels = df$parameters, ordered = T)
best = 5
df$color[best] = "red"
df
#> parameters color
#> 1 paramters_1 black
#> 2 paramters_2 black
#> 3 paramters_3 black
#> 4 paramters_4 black
#> 5 paramters_5 red
#> 6 paramters_6 black
#> 7 paramters_7 black
#> 8 paramters_8 black
#> 9 paramters_9 black
#> 10 paramters_10 black
p = ggplot(df, aes(y = parameters)) theme(axis.text.y = element_markdown(color = df$color))
q = p scale_y_discrete(guide = guide_axis(check.overlap = T))
Created on 2021-09-21 by the reprex package (v2.0.0)
CodePudding user response:
I don't think the aim of ggtext is to allow vectorised colour assignments through the theme elements. It instead offers to interpret (a limited set of) markdown/html tags in the labels, so if you want one specific label to be red, you should construct the html tag for red text for it.
library(ggplot2)
library(ggtext)
#> Warning: package 'ggtext' was built under R version 4.1.1
N = 10
df = data.frame(parameters = paste("paramters", seq(N), sep = "_"))
df$parameters = factor(df$parameters, levels = df$parameters, ordered = T)
best = 5
levels(df$parameters) = ifelse(
levels(df$parameters) == paste("paramters", best, sep = "_"),
paste0("<span style='color:red'>", levels(df$parameters), "</span>"),
paste0("<span style='color:black'>", levels(df$parameters), "</span>")
)
(p = ggplot(df, aes(y = parameters))
theme(axis.text.y = element_markdown()))
(q = p
scale_y_discrete(guide = guide_axis(check.overlap = T)))
Created on 2021-09-21 by the reprex package (v2.0.1)