Go back to Home

Rearrange the order of bars in Barplot [R]

While I was doing my California Housing Analysis, I had faced a problem where the bars of my barplots were not in the order they were supposed to be in.

barplot( height = rowsum(household_income_inland$households,household_income_inland$incomecut)[,1]
         , las = 1
         , col = "#A3A500"
         , border = NA  # eliminates borders around the bars
         , main = "Households by Median Income (INLAND)"
         , ylab = "count of households"
         , xlab = "Age"
         , ylim = c(0,1400000)
)

Screen Shot 2019-01-19 at 10.07.14 PM

You can see from the plot above that the bars are not in chronological order (10k-20k,20k-30k). The reson this happens because R arranges the labels in assending order. (special characters < 0 < 1 < 2.....)

The way I solved this problem was by creating a character vector "headers_income" of the bar labels in order.

headers_income <- c("0-10k", "10k-20k", "20k-30k","30k-40k", "40k-50k", "50k-60k","60k-70k","70k-80k","80k-90k","90k-100k" 
                    ,"100k-110k","110k-120k","120k-130k","130k-140k","140k-150k"," >150k")

Then I wrote "[headers_income]" at the end of the rowsum() function.

barplot( height = rowsum(household_income_inland$households,household_income_inland$incomecut)[,1][headers_income]
         , las = 1
         , col = "#A3A500"
         , border = NA  # eliminates borders around the bars
         , main = "Households by Median Income (INLAND)"
         , ylab = "count of households"
         , xlab = "Age"
         , ylim = c(0,1400000)
)

Done the Bars are now in order

Screen Shot 2019-01-19 at 10.06.40 PM