Elias Schoof
Elias Schoof

Reputation: 2046

Set different margins for left and right side

I know how to increase the margin on both sides in matplotlib:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.set_xmargin(0.3)   

ax.plot(range(10), np.random.rand(10))
plt.show()

enter image description here

However, I would like to have a margin only on the right side: something like ax.set_xmargin(left=0.0, right=0.3). Is that possible? I cannot set the axis limits manually because the plot is animated and the data change at every step.

Upvotes: 4

Views: 3441

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339102

There is an old feature request for this, which is still open. So, no, you cannot set the margins independently as of any current version of matplotlib.

Of course you may write your own function to do what you want.

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.plot([1,2,3],[1,3,1])

def set_xmargin(ax, left=0.0, right=0.3):
    ax.set_xmargin(0)
    ax.autoscale_view()
    lim = ax.get_xlim()
    delta = np.diff(lim)
    left = lim[0] - delta*left
    right = lim[1] + delta*right
    ax.set_xlim(left,right)

set_xmargin(ax, left=0.05, right=0.2)

plt.show()

Using this in an animation would require to call it in each animation step. This may slow down the animation a bit, but should still be fine for most applications.

Upvotes: 7

Related Questions