0

matplotlib automatically adds some small margin to plots so make them pretty:

import matplotlib.pyplot as plt
plt.plot([1,2,3],[2,3,4])

the actual xlim is (0.9, 3.1) (as returned by axes.get_xlim()) instead of (1,3) dictated by the data.

This is usually reasonable except for percent plots where the limits are (-80%,120%) which makes for 40/140 wasted space.

How is this extra margin computed? How can I affect it? (other than passing data max/min to set_xlimit).

sds
  • 58,617
  • 29
  • 161
  • 278
  • 1
    The extra space is a margin, which can be removed with `ax.margins(0)`. See [`matplotlib.pyplot.margins`](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.margins.html): *The padding added to each limit of the Axes is the margin times the data interval* – Trenton McKinney Jun 13 '23 at 21:23
  • To add on to @TrentonMcKinney's answer, when using MATLAB-like plotting rather than the object-oriented approach (see the [usage guide](https://matplotlib.org/3.5.0/tutorials/introductory/usage.html)), you will need to do `plt.margins(0)`. – jared Jun 13 '23 at 21:30
  • @jared it's call the implicit "pyplot" interface, whereas "axes" is the explicit interface. https://matplotlib.org/stable/users/explain/api_interfaces.html#api-interfaces – Trenton McKinney Jun 13 '23 at 21:34
  • 1
    @TrentonMcKinney Thanks for the link. I will be sure to use that verbiage in the future. – jared Jun 13 '23 at 21:36

0 Answers0