无法重置轴

5

我试图绘制一个圆和其中随机分布的一组点。据我所知,可以将任意数量的图形添加到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()

但解释器返回以下错误:

值错误:无法重置轴。您可能正在尝试在多个不支持的轴中重复使用艺术家

我的愚蠢错误在哪里?!


你可能在ax.add_artist(scatt)这一行遇到了错误。 - ksai
@ksai:那行代码只是在已定义的ax上添加了另一个“plot”,是吗? - user1393214
我尝试注释掉两个“artist”行,但我仍然得到两个图。让我研究一下。 - ksai
@ksai:我需要将 scattcircle 同时显示在一个 ax 中,就像是一个统一的图形。 - user1393214
@Roboticist 对不起,我的意思可能不太清楚,我刚刚发布了答案,请看一下。 - jedwards
显示剩余2条评论
1个回答

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

产生的结果

覆盖的图形

唯一的区别是我通过plt.subplots()创建了一个单独的轴对象,调用了轴方法ax.scatter()ax.add_patch(Circle(...))来在其上绘制。

我猜测你调用的plt.__方法会创建它们自己的分离轴,然后你尝试使用add_artist进行“合并”,从而导致错误。


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