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
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):
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()