-1

I have a table like this: dput of data

dput(data)
structure(list(status = c("Recovered", "Dead", "On-Treatment"
), northern_countries = c(24130778L, 955048L, 15634207L), Southern_countries = c(9157967L, 
308243L, 726474L)), class = "data.frame", row.names = c(NA, -3L
))

        status northern_countries Southern_countries
1    Recovered           24130778            9157967
2         Dead             955048             308243
3 On-Treatment           15634207             726474

I would like to create a stacked bar plot that shows the percentage of Dead, Recovered and On treatments which 2 bars are northern_countries and southern_countries.

I've been searching around but couldn't find the answer :( Also I've just started with R so please if could you elucidate things in details I'd be much appreciated.

Thanks so much xoxo

AnilGoyal
  • 25,297
  • 4
  • 27
  • 45
  • Though you have not included the it is clear that you need to pivot_longer your data (last 2 columns) before making a chart – AnilGoyal Nov 12 '20 at 12:01
  • `data %>% pivot_longer(cols = c(northern_countries, Southern_countries), names_to= "countries", values_to = "value") %>% ggplot(aes(x=status, y=value)) + geom_col(aes(fill= countries), position = "dodge")` try this – AnilGoyal Nov 12 '20 at 12:23
  • Remember in R, the data to be plotted on one axis should be in one column only. This is unlike MS excel where data on two columns can be plotted on one axis. – AnilGoyal Nov 12 '20 at 12:26

1 Answers1

0

Using ggplot2:

Say df is the name of your data frame, first you need to transform it to long format with pivot_longer() from the tidyr package:

df <- tidyr::pivot_longer(df, cols=-1)

Obs: The -1 wont transform the first row into long. Then it should look something like this (sorry for bad quality):

enter image description here

So we want the name column in the x axis (one bar for each value in it), value in y, and each bar should be divided in colors by status, so we pass it to fill:

library(ggplot2)

ggplot(df, aes(x=name, y=value, fill=status) + geom_col()