Home > front end >  R ggplot2 multiple column stacked histogram, separate bar for each column
R ggplot2 multiple column stacked histogram, separate bar for each column

Time:10-02

I am trying to make a histogram of percentages for multiple columns of data in one graph. Is there a way to do this without transforming the data into an even longer format? Basically, I want to combine multiple histograms on one plot with the same y axis. I can't get facet_grid and facet_wrap to work because everything is in different columns. Here is some sample data:

data <- data.frame("participant"=c(1,2,3,4,5),
                   "metric1"=c(0,1,2,0,1),
                   "metric2"=c(1,2,0,1,2),
                   "metric3"=c(2,0,1,2,0),
                   "date"=rep("8/14/2021",5))

Ideally, I would have a stacked bar for metric 1, next to that a stacked bar for metric 2, fianlly a stacked bar for metric 3. I can generate one stacked bar at a time with the following code:

ggplot(data = data, 
       aes(x = date, group = factor(metric1), fill=factor(metric1)))    
  geom_bar(position = "fill")   
  scale_y_continuous(labels = scales::percent) 

How do I combine this graph with the graphs for metric 2 and 3 so that they are all on the same graph with the same axes? Can it be done without making the data long? My real data is more complicated than the test data, and I'd like to avoid transforming it. Thank you for reading and any help you can offer.

CodePudding user response:

Reshape to 'long' format with pivot_longer and create the bar plot

library(dplyr)
library(ggplot2)
library(tidyr)
data %>% 
   pivot_longer(cols = starts_with('metric'), values_to = 'metric') %>% 
   ggplot(aes(x = date, group = factor(metric),fill = factor(metric)))    
       geom_bar()      
      facet_wrap(~ name)
  • Related