Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a stacked bar chart in r with ggplot

My data is:



positive <- c("21", "22", "33", "21", "27") ##Percentage
negative<- c("71", "77", "67", "79", "73")  ##Precentage 
sample <- c("Hr", "Fi", "We", "Pa", "Ki")
mydata <- data.frame(positive , negative, sample)

I want to create a stacked bar graph that shows positive and negative percentages for each category in the sample variable. I tried this:

ggplot(mydata) +
  geom_bar(aes(x = sample, fill = positive))

but did not wrok. Sorry if the question looks basic. I started R a few weeks ago.

like image 420
Santiago99 Avatar asked Sep 15 '25 12:09

Santiago99


2 Answers

This probably serves your purpose:

library(tidyverse)
mydata %>% pivot_longer(cols = !sample, names_to = "status", values_to = "percentage") %>% 
 ggplot(aes(fill = status, x = sample, y = percentage)) + 
 geom_bar(position = "stack", stat = "identity")

The result: enter image description here

like image 105
Abdur Rohman Avatar answered Sep 17 '25 03:09

Abdur Rohman


You need to pivot your data to long format first (tidy format). Then, we can specify the x (sample), y (value), and fill (name) conditions.

library(tidyverse)

mydata %>%
  pivot_longer(-sample) %>%
  ggplot(aes(fill = name, y = value, x = sample)) +
  geom_bar(position = "stack", stat = "identity")

Output

enter image description here

like image 42
AndrewGB Avatar answered Sep 17 '25 02:09

AndrewGB