设置AxisArtist的轴限制plt.圆在matplotlib中

2024-10-03 06:32:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我画一个圆:

import matplotlib.pyplot as plt
from mpl_toolkits.axisartist.axislines import SubplotZero

fig = plt.figure(1, figsize=(6, 6))

ax = SubplotZero(fig, 111)
fig.add_subplot(ax)

centreCircle = plt.Circle((0, 0), 1, color="black", fill=False, lw=2)

# Draw the circles to our plot
ax.add_patch(centreCircle)
plt.axis('equal')
plt.show()

一切正常:

enter image description here

但是当我想增加轴的极限时:

ax.set_ylim(-5, 5)
ax.set_xlim(-5, 5)

我失败了。你知道吗

我怎样才能做到呢?你知道吗


Tags: fromimportaddmatplotlibasfigpltax
3条回答

你只需要

ax.set_ylim(-5, 5)

甚至

plt.ylim(-5, 5)

我可能不完全理解这个问题,因为仅仅在代码中添加ax.set_ylim(-5, 5); ax.set_xlim(-5, 5)实际上会产生一个很好的绘图。你知道吗

但一般来说,当使用相等纵横比时,可以使用ax.set_aspect("equal", adjustable="box")使轴调整到您的限制。所以对于不对称极限,这看起来像

import matplotlib.pyplot as plt
from mpl_toolkits.axisartist.axislines import SubplotZero

fig = plt.figure(1, figsize=(6, 6))

ax = SubplotZero(fig, 111)
fig.add_subplot(ax)

centreCircle = plt.Circle((0, 0), 1, color="black", fill=False, lw=2)

# Draw the circles to our plot
ax.add_patch(centreCircle)
ax.set_aspect("equal", adjustable="box")

ax.set_ylim(-5, 5)
ax.set_xlim(-5, 10)

plt.show()

enter image description here

你可以简单地执行你需要的,而不需要艺术家。如果您可以不使用它,那么下面是以下示例代码:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Circle

fig, ax = plt.subplots(1,1, figsize=(7,7))
ax.add_artist(Circle((0,0),1,color='b'))
ax.set_xlim((-5,5))
ax.set_ylim((-5,5))

plt.show()

编辑:使用AxisArtist重做

import matplotlib.pyplot as plt
import mpl_toolkits.axisartist as AA
%matplotlib "notebook"

fig = plt.figure(1, figsize=(5,5))
ax = AA.Subplot(fig, 1, 1, 1)
fig.add_subplot(ax)
centreCircle = plt.Circle((0, 0), 1, color="black", fill=False, lw=2)
ax.add_patch(centreCircle)
ax.set_ylim(-5, 5)
ax.set_xlim(-5, 5)
plt.show()
plt.savefig('circle5x5v2.png')

enter image description here

相关问题 更多 >