Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R style data-axis buffer in matplotlib

R plots automatically set the x and y limits to put some space between the data and the axes. I was wondering if there is a way for matplotlib to do the same automatically. If not, is there a good formula or 'rule of thumb' for how R sets its axis limits?

like image 239
Tyler F Avatar asked Nov 21 '12 02:11

Tyler F


2 Answers

In matplotlib you can achieve this by setting the margins

import matplotlib.pyplot as plt 

fig, ax = plt.subplots()
ax.margins(0.04)
data = range(1, 11) 
ax.plot(data, 'wo') 
plt.savefig('margins.png')

margins

However, it doesn't seems, that there is an rc parameter to get this automatically.

Update 4/2013

The possibility to add an rc param for the margins is now in matplotlib master (Thanks @tcaswell). So it should work with the next matplotlib release (current release is 1.2.1).

like image 138
bmu Avatar answered Sep 20 '22 21:09

bmu


Looking at ?par for the parameter xaxs:

The style of axis interval calculation to be used for the x-axis. Possible values are "r", "i", "e", "s", "d". The styles are generally controlled by the range of data or xlim, if given.
Style "r" (regular) first extends the data range by 4 percent at each end and then finds an axis with pretty labels that fits within the extended range.

So if we try this out:

par(xaxs="r")       #The default  
plot(1:10, 1:10)

enter image description here

We can actually demonstrate that it's +/- 4% of the range on each side:

abline(v=1-(diff(range(1:10)))*0.04, col="red")
abline(v=10+(diff(range(1:10)))*0.04, col="red")

enter image description here

like image 23
sebastian-c Avatar answered Sep 22 '22 21:09

sebastian-c