设置左右两侧不同的边距。

3

我知道如何在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

然而,我只想在右边有一个边距:类似于 ax.set_xmargin(left=0.0, right=0.3)。这可能吗? 由于图表是动态的且数据在每个步骤中都会更改,因此我无法手动设置轴限制。
1个回答

6

这方面已经有一个旧的功能请求,目前仍然保持开放状态。因此,无论是哪个版本的matplotlib,都无法独立设置边距。

当然,您可以编写自己的函数来实现所需功能。

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

在动画中使用这个需要在每个动画步骤中调用它。这可能会稍微减慢动画的速度,但对于大多数应用程序来说仍然可以接受。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接