Home > Enterprise >  how to plot a stacked bar with the following dataframe
how to plot a stacked bar with the following dataframe

Time:03-05

dataframe is below

 tata4 <- data.frame(Subtype = c("Prostate", "Oesophagus", "Lung"),  
alive = c(88, 22, 100), dead = c(12, 55, 17), 
uncertain = c(10, 2, 2), total = c(186,46,202))  

what I want is this - A stacked barplot for each of the 'prostate', 'oesophagus and Lung. The columns should be subdivided vertically into the number alive,dead and uncertain according to each cancer. (with each bar displaying the total).

I'm struggling to find the right codes. I can't seem to find a way of making the 'fill' function the values of each tumour site.

Can someone please help.

CodePudding user response:

First you need to bring your data into long format:

tata4 <- pivot_longer(tata4, cols = 2:4, names_to = "Status", values_to = "Count")

Afterwards you can feed the data to ggplot:

ggplot(tata4, aes(Subtype, Count, fill = fct_rev(Status)))  
  geom_col()

Which gives:

enter image description here

I am not sure where you want to plot or annotate the total

CodePudding user response:

Many thanks, solved the problem!

  • Related