Home > Software engineering >  Customize Each Row of Stacked Horizontal bar plot by percentage
Customize Each Row of Stacked Horizontal bar plot by percentage

Time:09-05

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()

enter image description here

Thanks!

CodePudding user response:

You can arrange your data with group_by for your "type" by "value" and set group = type in your aes like this:

library(tibble)
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))

library(ggplot2)
library(dplyr)
ggplot(mydata %>% group_by(type) %>% arrange(-value, by_group = TRUE), aes(x = type, y = value, fill = id, group = type))  
  geom_col(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()

Created on 2022-09-04 with reprex v2.0.2

  • Related