Matplotlib:使轴适合形状限制

时间:2019-01-17 01:20:20

标签: python python-3.x matplotlib

我正在尝试使用以下代码在matplotlib中绘制一个矩形:

import matplotlib.pyplot as plt
import matplotlib.patches as patches

fig, ax = plt.subplots()
width = 20
height = 10

rect = patches.Rectangle((0,0),width, height, linewidth=4,edgecolor='r',facecolor='none')
ax.add_patch(rect)

plt.show()

这将导致:

enter image description here

在这种情况下,轴不适合矩形限制。我可以用以下方法解决它:

import matplotlib.pyplot as plt
import matplotlib.patches as patches

fig, ax = plt.subplots()
width = 20
height = 10

ax.set_xlim(0,width)
ax.set_ylim(0,height)

rect = patches.Rectangle((0,0),width, height, linewidth=4,edgecolor='r',facecolor='none')
ax.add_patch(rect)

plt.show()

这给了我下面的图片来解决这种情况下的问题:

enter image description here

但是,当我试图在同一图中绘制许多矩形和其他形状时,我需要一种方法matplotlib能够聪明地确定自身的正确轴限制,就像在绘制法线图时一样。

1 个答案:

答案 0 :(得分:2)

您正在寻找.autoscale()。您可以使用.margins(0)删除默认情况下添加的所有多余空间。

import matplotlib.pyplot as plt
import matplotlib.patches as patches

fig, ax = plt.subplots()
width = 20
height = 10

rect = patches.Rectangle((0,0),width, height, linewidth=4,edgecolor='r',facecolor='none')
ax.add_patch(rect)
ax.margins(0)
ax.autoscale()

plt.show()

enter image description here