Home > database >  How to plot multiple bar plots with same x values, different y values, and final product is similar
How to plot multiple bar plots with same x values, different y values, and final product is similar

Time:06-09

I have a dataset that has one column as x value for all other columns, and different y values, which are those other columns that looks like this (data frame is called freq_dist):

Duration D0 D1 D2 D3 D4
1 130 101 53 30 10
2 23 36 13 9 0

I want to set duration (column 1) as x value for all other columns, and display a bar chart using ggplot2 function. I tried to use geom_bar but instead of returning the values I already have in the table as my y values, it returns the counts of the occurance of each value, so instead of geom_bar, geom_col might be what I want, but how do I set my column 1 as the fixed x value for all other columns? I also tried to use simple barplot() function, which is essentially what I'm looking for, like this:

xx = freq_dist[,1]
yy = freq_dist[,2]

barplot(yy~xx)

Thanks all!

CodePudding user response:

library(tidyverse)
freq_dist %>%
  pivot_longer(-1) %>%
  ggplot(aes(as.factor(Duration), value))  
  geom_col()  
  theme_classic()  
  facet_wrap(~name)  
  labs(x = "Duration")

enter image description here

CodePudding user response:

You need to pivot into long format and use geom_col

ggplot(pivot_longer(freq_dist, -1), aes(factor(Duration), value, fill = name))  
  geom_col(width = 0.5)  
  scale_fill_brewer(palette = "Set1")  
  theme_light(base_size = 16)  
  labs(x = "Duration", fill = NULL)  
  facet_wrap(~name)  
  theme(legend.position = c(0.84, 0.25))

enter image description here

  • Related