OUseful.Info, the blog…

Trying to find useful things to do with emerging technologies in open education

Setting Axis Limits on ggplot Charts

I’ve been doodling some chart in R/ggplot using geom_text() to generate a labelled scatterplot.

The chart actually builds up several layers using different datasets, so it’s not obvious how to set the ranges cleanly: I know the lower bound I want for the y-axis (y=0), but I want to let the upper bound float.

There’s also an issue with the labels overflowing the edges left and right.

exampleChart_badLimits

So here are a couple of lines to make everything better (chart is in g):

#Find the current ymax value for upper bound
#(via http://stackoverflow.com/questions/7705345/how-can-i-extract-plot-axes-ranges-for-a-ggplot2-object#comment24184444_8167461 )
gy=ggplot_build(g)$panel$ranges[[1]]$y.range[2]
g=g+ylim(0,gy)

#Handle the overflow by expanding the x-axis
g=g+scale_x_continuous(expand=c(0.1,0))

plot_neater

Written by Tony Hirst

December 3, 2013 at 12:41 pm

Posted in Rstats

Follow

Get every new post delivered to your Inbox.

Join 728 other followers

%d bloggers like this: