7

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?

sebastian-c
  • 15,057
  • 3
  • 47
  • 93
Tyler F
  • 83
  • 1
  • 5

2 Answers2

7

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).

bmu
  • 35,119
  • 13
  • 91
  • 108
  • This is the right answer. Not sure why the other answer was chosen since the question was asking about Python's matplotlib and not R's plot() (R was just used as a comparison). – Reuben L. Jan 21 '14 at 20:05
6

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

sebastian-c
  • 15,057
  • 3
  • 47
  • 93