Creating a stacked bar chart in R

101 Views Asked by At

I have a matrix with 10 rows and 2 columns, I want to create a bar chart which is stacked by rows but it is getting stacked by columns. This is my code for the matrix

population_matrix<-matrix(c(filter_data$Rural.population,
                           filter_data$Urban.population),
                           nrow = 10,ncol = 2,byrow = FALSE)

And, this the code for bar chart

barplot(population_matrix/1000000,
         xlab = "States",ylab = "Population (in Millions)",
         col = c("Green","Blue"),
         main = "Statewise population",
         border = "Black")

I wanted columns rural population and urban population to be stacked for each state differentiated by colors. Instead rural population got stacked in one column while urban population got stacked in another.

1

There are 1 best solutions below

0
jay.sf On

I believe you have data like this

#    country rural urban
# 1        A    17    34
# 2        B    48    39
# 3        C    40    12
# ...

and can directly do:

barplot(t(dat[2:3]),  ## or `dat[c('rural', 'urban')]`
        xlab="States", ylab="Population (in Millions)",
        col=3:4,
        main="Statewise population",
        border="Black",
        names.arg=dat$country,
        legend.text=c('rural', 'urban'))

enter image description here


Data:

dat <- structure(list(country = c("A", "B", "C", "D", "E", "F", "G", 
"H", "I", "J"), rural = c(46, 47, 20, 43, 35, 30, 39, 14, 36, 
38), urban = c(27, 38, 47, 19, 27, 47, 49, 13, 28, 32)), class = "data.frame", row.names = c(NA, 
-10L))