R – Pretty Axis with Min and Max labels

axis-labelsr

I want to draw a simple bar plot like so:

test <- data.frame(y=c(1,3,53,10,30,35,50), x=c(1:7))
barplot(test$y, names.arg=test$x)

resulting graph

My issue is that the y axis does not extend far enough if the maximum value is some "unpretty" number. What would be better is if the axis extended passed the maximum value and finished on some "pretty" value greater than the maximum.

Given a random dataset (i.e. this is going in a function), is there a simple way of doing this?

Best Answer

You can use a combination of pretty() and range() to automatically pick nicer settings for ylim:

test <- data.frame(y=c(1,3,53,10,30,35,50), x=c(1:7))
barplot(test$y, names.arg=test$x, 
        ylim = range(pretty(c(0, test$y))))

enter image description here

(Thanks to Gavin Simpson for pointing out that range(pretty(c(0, test$y))) works just as well as range(pretty(c(0, max(test$y))))