Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a stacked bar plot for multiple variables - ggplot2 in R

Tags:

r

ggplot2

I have some problems with making a stacked bar chart in ggplot2. I know how to make one with barplot(), but I wanted to use ggplot2 because it's very easy to make the bars have the same height (with 'position = 'fill'', if I'm not mistaken).

My problem is that I have multiple variables that I want to plot on top of each other; my data looks like this:

dfr <- data.frame(
  V1 = c(0.1, 0.2, 0.3),
  V2 = c(0.2, 0.3, 0.2),
  V3 = c(0.3, 0.6, 0.5),
  V4 = c(0.5, 0.1, 0.7),
  row.names = LETTERS[1:3]
)

What I want is a plot with categories A, B, and C on the X axis, and for each of those, the values for V1, V2, V3, and V4 stacked on top of each other on the Y axis. Most graphs that I have seen plot only one variable on the Y axis, but I'm sure that one could do this somehow.

How could I do this with ggplot2? Thanks!

like image 829
Annemarie Avatar asked Jul 14 '11 12:07

Annemarie


People also ask

How do you plot multiple bar graphs in R?

Where x-axis represents the name of the data and y-axis represents the bar graph values from 0 to n range. Hence, to draw multiple barplots side by side the data for each barplot is initialized and combined using cbind(). Then it is actually plotted using barplot() with beside set to TRUE(T).

How do you do a grouped Barplot in R?

The user needs to first modify the data used to create the bar charts accordingly into different groups and then has to call the barplot() function with the required parameters passed into it to create the barplot of the given data respectively in the R programming language.


1 Answers

You could also do like this

library(tidyverse)
dfr %>% rownames_to_column("ID") %>% pivot_longer(!ID) %>%
  ggplot() +
  geom_col(aes(x = ID, y = value, fill = name), position = 'fill')

enter image description here

like image 146
AnilGoyal Avatar answered Sep 29 '22 13:09

AnilGoyal