I was answering this question where @Léo wanted a barplot with stat = "identity"
and position = "identity"
. This causes the bars (one for every value of the fill
aesthetic) to get on top of eachother, making some to get hidden:

His solution was to set alpha = 0.5
, but he didn't liked the result as the colors mixed in different ways in each x-axis tick. Thus, i figured that the solution would be to have a different color ordering for each x-axis tick, but i don't know how to do it in ggplot.
What I've tried:
Dummy data:
library(tidyverse)
set.seed(7)
df = tibble(
categories = rep(c("a", "b", "c"), each = 3) %>% factor(),
xaxis = rep(1:3, 3) %>% factor(),
yaxis = runif(9))
What plotted the "original" graph, shown above:
ggplot() +
geom_bar(aes(xaxis, yaxis, fill = categories), df,
stat = "identity", position = "identity")
My attempt: changing the categories
levels order and creating a different geom_bar
for each x-axis value with a for loop:
g = ggplot()
for(x in unique(df$xaxis)){
df.x = df %>% filter(xaxis == x) %>% mutate(categories = fct_reorder(categories, yaxis))
g = g + geom_bar(aes(xaxis, yaxis, fill = categories), df.x,
stat = "identity", position = "identity")}
plot(g)
The levels on df.x actually change to the correct order for every iteration, but the same graph as before gets produced.