Side By Side Bar Graphs Using R and ggplot2

Hi. I was experimenting with trying to get side by side bar graphs in R and the ggplot2 package.


Table Of Contents


Simulated Coin Flip Data

The ggplot2 package is first loaded into R.

We have two players A and B who each an unfair coin. This unfair coin has a 30% chance of getting heads and
a 70% chance of getting tails. Both players flip this coin 1000 times each. This can be simulated in R using the sample() function.

We can see the results of the coin flips using the table() function.

The next lines of code is about putting the results together in a data table format.

These coin flip results can be converted into a two by two table as a different visual. For graphing purposes, this 2 by 2 table is converted into a data frame.


Side By Side Bar Graphs

To obtain side by side bar graphs in ggplot2, we need a lot of parts on top of the ggplot() command.

  1. geom_bar(stat = “identity”, position = position_dodge(), alpha = 0.75) gives the side by side bar graphs
  2. ylim(0, 800) gives limits on the y-axis values
  3. The geom_text() line adds labels to the bar graphs. Note that position_dodge is needed as we used position dodge was used in geom_bar().
  4. labs() gives labels depending on what is specified
  5. The theme() function allows for additional aesthetic options such as a centered title and font sizes.


Using facet_grid()

In the above plot, we have four bars in one graph where the Player A bars are beside the Player B bars. Adding facet_grid(. ~Player) will turn this bar graph plot in a way where there is one bar graph plot for Player A and another bar graph plot for player B right beside it.

Note that the position_dodge() options were removed as they are not needed. To highlight the Player A and Player B font text and the bars, the strip.background and strip.text options are used.


References

  • http://www.cookbook-r.com/Graphs/Bar_and_line_graphs_(ggplot2)/
  • R Graphics Cookbook by Winston Chang (2012)

Leave a Reply