Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different Starting Point (not 0) in barplot Y-Axis?

Tags:

r

I am trying to create a simple bar graph including two bars showing the average math scores of two groups of students. The averages are 363.2 and 377.4. creating bar graph is simple. What I'd like to do is to have my y-axis starts from 340 rather than 0. I do know how to change the limits of y-axis, but the issue is when I change the limit of y-axis to c(340, 380), R still draws the whole bar which most of it is below the x-axis!

Here is my code:

barplot(c(363.2, 377.4), beside = T, ylim = c(340,380), col = c("orange", "blue"))

I've also attached my plot:

like image 966
Xiaochuan Zhang Avatar asked Jul 27 '12 20:07

Xiaochuan Zhang


2 Answers

Adding xpd=FALSE and re-adding the horizontal axis works, sort of:

b <- barplot(c(363.2, 377.4), beside = TRUE, 
   ylim = c(340,380), col = c("orange", "blue"),xpd=FALSE)
axis(side=1,at=b,labels=c("group 1", "group 2"))
box(bty="l")

I claim (I can't point you to a definitive reference, although Googling "bar plot zero axis" seems to come up with useful stuff; perhaps others will chime in) that it is bad practice to draw bar graphs where the vertical axis does not include zero: the argument is that the viewer will assume that bar graphs are anchored to the origin (this argument is more commonly made when explaining why R doesn't make it easy to use a logarithmic axis for barplots: see comments here, for example). Those who feel this way would say you should use points to indicate the value instead; in this case the implicit assumption of zero-anchoring does not hold as strongly.

In other words, "here's how you can do this -- but you shouldn't" ...

like image 184
Ben Bolker Avatar answered Sep 30 '22 18:09

Ben Bolker


The following can be seen if you look at ?barplot:

"xpd: logical. Should bars be allowed to go outside region?"

You just need to include xpd=FALSE in your parameters for the barplot.

like image 22
Edward Avatar answered Sep 30 '22 18:09

Edward