I have the following simple MWE.
set.seed(2022102517)
df <- data.frame(letter =factor(colors()[1:8], levels = colors()[1:8]), value = rnorm(8))
library(ggplot2)
ggplot(data = df, aes(x = letter, y = value, group = 1)) + geom_line()
Which gives me a line plot for "value" for each "letter" as follows:
Note the ordering.
Now, what I would like to do is to have a small square in front of each colorname of different (assigned) color (from fill.col) (in the x-axis). So, basically, wherever we have a letter on x-axis, then add a filled color box to the left of each letter, where the colors are picked up from,say, fill.col.
fill.col <- c("#005A32", "#FC8D62", "#D95F02", "#8DA0CB", "#7570B3", "#E78AC3", "#E7298A", "#A6D854")
I tried the following (from the solution provided below):
library(tidyverse)
library(RColorBrewer)
library(ggtext)
df %>%
mutate(new_letter = paste("<span style = 'color: ",
fill.col,
";'>",
"\u25a0",
"</span>",
" ",
letter,
sep = ""),
new_letter = fct_reorder(new_letter, as.character(letter))) %>%
ggplot(aes(new_letter, value, group = 1)) +
geom_line() +
theme(axis.text.x = element_markdown(size = 12))
which gives me:
It appears to me that in this case, we are reordering "letter" by the alphabet, though the color attachments appear to be correct here. Is it possible to keep the original order so that I can have control on the display? Thanks for further help and clarifications!