python - 无法重置轴

标签 python numpy matplotlib

我正在尝试绘制一个圆和其中一组随机分布的点。 AFAIK,可以向 ax 对象添加任意数量的数字。所以,这是我的方法:

import numpy as np
import matplotlib.pyplot as plt

x = np.random.uniform(1,5,size=1000)
theta = np.random.uniform(0.55*np.pi,1.2*np.pi,size=1000)
y = [i*np.tan(j) for i,j in zip(x,theta)]

xx = np.random.uniform(0,1,size=1000)
yy = np.random.uniform(0,1,size=1000)

for i in range(len(xx)):
    if xx[i]>yy[i]:
        xx[i],yy[i] = yy[i],xx[i]

R = 5

xxx = [j*R*np.cos(2*np.pi*i/j) for i,j in zip(xx,yy)]
yyy = [j*R*np.sin(2*np.pi*i/j) for i,j in zip(xx,yy)]

circle = plt.Circle((0, 0), 5, color='b', fill=False)
scatt = plt.scatter(yyy,xxx)

fig, ax = plt.subplots()

ax.add_artist(circle)
ax.add_artist(scatt)

plt.ylabel("scatter")
plt.xlabel("Data")

plt.show()

但是解释器返回以下错误:

ValueError: Can not reset the axes. You are probably trying to re-use an artist in more than one Axes which is not supported

我犯了什么愚蠢的错误?!

最佳答案

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

x = np.random.uniform(1,5,size=1000)
theta = np.random.uniform(0.55*np.pi,1.2*np.pi,size=1000)
y = [i*np.tan(j) for i,j in zip(x,theta)]

xx = np.random.uniform(0,1,size=1000)
yy = np.random.uniform(0,1,size=1000)

for i in range(len(xx)):
    if xx[i]>yy[i]:
        xx[i],yy[i] = yy[i],xx[i]

R = 5

xxx = [j*R*np.cos(2*np.pi*i/j) for i,j in zip(xx,yy)]
yyy = [j*R*np.sin(2*np.pi*i/j) for i,j in zip(xx,yy)]

#circle = plt.Circle((0, 0), 5, color='b', fill=False)
#scatt = plt.scatter(yyy,xxx)

fig, ax = plt.subplots()

#ax.add_artist(circle)
#ax.add_artist(scatt)

ax.scatter(yyy,xxx)
ax.add_patch(mpl.patches.Circle((0, 0), 5, color='b', fill=False))

plt.ylabel("scatter")
plt.xlabel("Data")

plt.axis('equal')       # Added, optional :)

plt.show()

生产

Overlayed plots

唯一的区别是我创建了一个轴对象(通过 plt.subplots()),称为轴方法 ax.scatter()ax.add_patch(Circle(...))在上面画画。

我的猜测是您调用的 plt.__ 方法正在创建它们自己的独立轴,然后您尝试将它们与 add_artist “合并”导致错误.

关于python - 无法重置轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50753721/

相关文章:

python - celery任务的动态注册

python - matplotlib 给定范围内的等高线图

python - 什么 matplotlib rc 参数控制图例标题大小?

python - 计算数据框中库存的重量

python - PyQt 从不同目录导入 QML 主题

python - 使用枚举

python - 将 RGB 数组转换为 HSL

python - 将正态分布拟合到一维数据

python - 从度数为 30 的 t 分布生成 100*2 数组

python - 如何在 Python 中的函数指定的域中绘制 3 维图?