A Sideways Bar Graph Example In R

Hi. I have been playing around R’s ggplot2 data visualization package and I have learned how to do sideways bar graphs.


Table Of Contents


References

  • http://rstudio-pubs-static.s3.amazonaws.com/7433_4537ea5073dc4162950abb715f513469.html
  • R Graphics Cookbook by Winston Chang (2012)


Favourite Colours Survey Data

I will illustrate how to create a sideways bar graph using made up survey data. This data will be based on people’s favourite colours.

The next lines of code consist of check the structure of the data, renaming the column names and computing the total number of people in the survey.


From Regular Bar Graph To A Sideways Bar Graph

The code for a regular (vertical) bar graph in R using ggplot2 would look like this.

 

 

To convert the above bar graph into a sideways one, just simply add coord_flip() after ggplot().

 

Notice that from bottom to top the colours are in ABC order. This is different than what we had earlier with what we had with colour_choices().


Retaining Order In Factors In A Bar Graph

We can retain the colour choices order we want with a minor fix. This fix can be done on the first column by convert the first column as a factor but with setting the vector colour_choices in the levels argument of factor().

The resulting sideways bar graph code is similar to the previous one. The resulting sideways bar graph will be different on the vertical axes with the colour choices.


Sorted Sideways Bar Graph

If we want to sort our bars from largest to smallest, we need to reorganize the factors in a specific way.

The order(colour_table$Count) part outputs the positions of the Count column in colour_table from largest to smallest. Then colour_table$Colour[order(colour_table$Count)] outputs the colours with the largest counts first to the less frequent colour.

Here is the code for the sorted sideways bar graph with the output.


Adding Labels To The Sorted Sideways Bar Graph

To make the bar graphs a bit more informative, labels can be added. The geom_text() function after ggplot() enables labels.

Leave a Reply