Bar Graphs in ggplot2

[This article was first published on Psychwire » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

As part of my continuing fun and games getting to grips with ggplot2′s vast multitude of functions, here I give a basic intro to plotting bar graphs. Bit by bit, I’m slowly creating my own library of code to call on when needed!

The Setup

Let’s begin by making up some data. This is for a pretend experiment with four participants (labelled “ppt1″, “ppt2″, and so on). They take part at two different time points (Time 1 and Time 2 – cool name or what). Some kind of stimulus is presented to them in different regions in the display. We’ll call these two “Region A” and “Region B”. Their performance is indicated by mean_score. Here is the code to generate some fake data – note the use of randomisation here with rnorm, meaning your means will be different to those I illustrate here:

ppt <- rep(c("ppt1", "ppt2", "ppt3", "ppt4"), 8 )
time<- c(rep("Time 1",8), rep("Time 2",8))
mean_score<-c(rnorm(8, mean=500, sd=20), rnorm(8, mean=250, sd=80))
region <- c(rep("Region A",4), rep("Region B",4),rep("Region A",4), rep("Region B",4))
bar_data<-data.frame(ppt,time, region, mean_score)

This leaves us with a shiny new dataframe called bar_data. 

The Bar Graphs / Bar Charts

Now for the code. What we want to do is take a look at how each participant scored, with their mean_score for each Time and each Region.

bars<-ggplot(bar_data)+
aes(x=region, y=mean_score)+
geom_bar()+
facet_grid(facets=ppt~time)
ggsave(bars, file="bars.png")

We set up the x and y axes using the aes command. geom_bar() draws up the bar chart. Next, all we need is facet_grid which creates a grid-like arrangement for various combinations of the different factor levels in the columns. We specify facets = ppt~time which tells ggplot to draw one bar chart for each level of ppt and time . Finally, ggsave is a handy way to output a high-dpi image straight out to your current working directory. This gives publication-quality plots in an instant. At last, we can rejoice as we find it gives us the following graph:


To leave a comment for the author, please follow the link and comment on their blog: Psychwire » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)