In a shiny app, I let users subset data, and then create a plot in which a categorical variable is reordered from higher to lower according to the value of another variable and displayed following the user input.
I would like color and fill to be linked to the category variable irrespective of the order.
Tried and not working solutions:
How to assign colors to categorical variables in ggplot2 that have stable mapping?
How to manually set colours to a categorical variables using ggplot()?
MWE:
data <- mtcars %>%
rownames_to_column() %>%
rowid_to_column() %>%
mutate(rowname = reorder(rowname, mpg))
plot <- data %>%
ggplot(aes(rowname, mpg, fill = rowname, color = rowname))+
geom_col()+
coord_flip()
plot %+% droplevels(filter(data, rowid < 3))
produces this:
while
plot %+% droplevels(filter(data, rowid < 4))
produces this:
In a nutshell:
Intended behavior: colors are matched to category irrespective of order of the plot.
Actual behavior: colors change depending on position of the category once reorder
ed.