Wondering why matplotlib pyplot won't adjust margins

Viewed 1516

I want to add margins to the plot so that rather than having the 0.0 be at the edge corner, the 0.0 is slightly away from the corner. I'm looking at the docs and it would seem that adding this line plt.margins(x_margin, y_margin) should add padding. My output below however still is the same regardless of that function call and still is missing margin padding.

enter image description here

Example code to produce:

import matplotlib.pyplot as plt
plt.plot([0, 0.1, 0.3, 0.5, 0.7, 0.9, 1], [0.16, 0.17, 0.18, 0.19, 0.2, 0.21, 0.22], 'ro')
plt.axis([0, 1, 0.15, 0.3])
# Create a 10% (0.1) and 10% (0.1) padding in the
# x and y directions respectively.
plt.margins(0.1, 0.1)
plt.show()
2 Answers

After plotting your data, try this instead:

x0, x1, y0, y1 = plt.axis()
margin_x = 0.1 * (x1-x0)
margin_y = 0.1 * (y1-y0)
plt.axis((x0 - margin_x,
          x1 + margin_x,
          y0 - margin_y,
          y1 + margin_y))

You have two contradicting statements here:
plt.axis([0, 1, 0.15, 0.3]) sets the x-axes limits to (0,1). This cannot be undone with plt.margins(0.1, 0.1).

Depending on what the aim is, you may

  • leave the axes to autoscale and set plt.margins(0.1, 0.1) to get 10% margins.
  • Calculate your desired limits taking into account 10% margins; e.g. as

    lim = [0, 1, 0.15, 0.3]
    plt.axis( [lim[i] +2*(i%2-.5)*(lim[i//2+1]-lim[i//2])*0.1 for i in range(4)] )
    
Related