I have data similar in structure to the data below, which I used to create the horizontal stacked bar plot below. What I would like is for each individual horizontal bar (for each of the types 1 through 4) to be ordered in such a way that the fill variable (id in this case) shows up in order of its percentage (highest-to-lowest) in that individual bar.
So, for example, the bar for type 4 (top bar) should have the colors ordered (from left-to-right) as cyan, purple, lime, red. The order of the colors for in the bar for type 3 should be (right-to-left) green,purple, cyan, red. And so on for the horizontal bars for types 2 and 1. Here is my code with data
set.seed(100)
mydata<-tibble(id=as.factor(rep(1:4,each=4)),type=as.factor(rep(1:4,4)),value=runif(16,0,100))
mydata.graph <- ggplot(mydata, aes(x = type, y = value, fill = id)) +
geom_col(position = position_fill(), color="black", size=0.1, width=0.65) +
scale_fill_manual(values=rainbow(4),
labels = c("1","2","3","4")) +
scale_y_continuous(labels = scales::percent) +
coord_flip()
Thanks!