Experiment
iris %>%
group_by(Species) %>%
summarize(mean_petal_width = mean(Petal.Width)) %>%
ungroup() ->
data
data |>
ggplot(aes(Species, mean_petal_width,
fill = Species)) +
geom_col(show.legend = FALSE) +
scale_fill_viridis_d() +
labs(x = NULL,
y = NULL,
title = "<span style = 'color: red;'>Virginica irises</span> have the largest average petal width") +
theme(plot.title = ggtext::element_markdown())
p <- last_plot()
fill_values <- layer_data(p)$fill
fill_var <- p$mapping$fill |> capture.output() %>% .[2] %>% str_extract("\\^.+") %>% str_remove("\\^")
fill_representations <- p$data %>% .[fill_var] %>% pull() %>% levels()
html_statements <- paste("<span style = 'color: ", fill_values,
"'>", fill_representations, "</span>")
grab_fill_info <- function(plot){
fill_values <- layer_data(plot)$fill
fill_var <- plot$mapping$fill |> capture.output() %>% .[2] %>%
str_extract("\\^.+") %>% str_remove("\\^")
fill_representations <- plot$data %>% .[fill_var] %>% pull() %>% levels()
html_statements <- paste("<strong><span style = 'color: ", fill_values,
"'>", fill_representations, "</span></strong>")
data.frame(fill_values, fill_representations, html_statements)
}
grab_fill_info(p)
## fill_values fill_representations
## 1 #440154FF setosa
## 2 #21908CFF versicolor
## 3 #FDE725FF virginica
## html_statements
## 1 <strong><span style = 'color: #440154FF '> setosa </span></strong>
## 2 <strong><span style = 'color: #21908CFF '> versicolor </span></strong>
## 3 <strong><span style = 'color: #FDE725FF '> virginica </span></strong>
for(i in 1:length(fill_values)){
start <- "virginica have the largest average petal width"
start <- start |> str_replace(fill_representations[i], html_statements[i])
start
}
auto_color_html <- function(x, fill_df ){
for(i in 1:nrow(fill_df)){
x <- x |> str_replace(fill_df$fill_representations[i], fill_df$html_statements[i])
}
x
}
auto_color_html("", grab_fill_info(p))
## [1] ""
data |>
ggplot(aes(Species, mean_petal_width,
fill = Species)) +
geom_col(show.legend = FALSE) +
scale_fill_viridis_d() +
labs(x = NULL,
y = NULL,
title = "The setosa iris has the smallest average petal width<br>and the virginica irises have largest average petal width<br> while versicolor is in-between") +
theme(plot.title = ggtext::element_markdown())
q <- last_plot()
q_fill_df <- grab_fill_info(q)
q +
labs(title = "The setosa iris has the smallest average petal width<br>and the virginica irises have largest average petal width<br> while versicolor is in-between" |>
auto_color_html(q_fill_df)) +
theme(plot.title = ggtext::element_markdown())
make_title_ggtext_colors <- function(plot){
out <- plot
plot_fill_df <- grab_fill_info(plot)
out$labels$title <- out$labels$title |>
auto_color_html(plot_fill_df)
print(out)
}
make_title_ggtext_colors(q)