Python节目显示一个空白的figu

2024-06-01 04:00:27 发布

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

我试图弄清楚为什么用这个代码显示一个额外的空白数字,应该只有两个数字,但是在其中一个是空的地方显示了三个。下面是一张图片,显示了发生了什么:

Figures

以下是我使用的代码:

f1 = plt.figure(1)
img=mpimg.imread(image_path)
imgplot = plt.imshow(img)

original_image = Image.open(image_path)
bw_image = original_image.convert('1', dither=Image.NONE)

bw_image_array = np.array(bw_image, dtype=np.int)
black_indices = np.argwhere(bw_image_array == 0)
chosen_black_indices = black_indices[np.random.choice(black_indices.shape[0], replace=False, size=3000)]

distances = pdist(chosen_black_indices) 
distance_matrix = squareform(distances)

optimized_path = solve_tsp(distance_matrix)

optimized_path_points = [chosen_black_indices[x] for x in optimized_path]
f2 = plt.figure(2)
plt.xlim(0, 600)  
plt.ylim(0, 800)  
plt.gca().invert_yaxis()  
plt.xticks([])  
plt.yticks([])
xstartdata = optimized_path_points[0][0]
ystartdata = optimized_path_points[0][1]
fig, ax = plt.subplots()
ln, = plt.plot([], [], color='black', marker='o', linestyle='dashed', markersize=1, animated=True)
plt.plot([xstartdata], [ystartdata], color='black', marker='o', linestyle='dashed', markersize=1,  lw=0.1)
plt.gca().invert_yaxis()
x = []
y = []

def init():
    ln.set_data([],[])

    return ln,

def animate(i):
    x.append(optimized_path_points[i][1])
    y.append(optimized_path_points[i][0])

    ln.set_data(x, y)
    plt.plot(x , y , lw=0.1,animated=True)
    return ln,

anim = animation.FuncAnimation(fig, animate, init_func=init,frames=range(len(optimized_path_points)), interval=5, blit=True)

plt.show()

Tags: pathimagetrueplotinitnppltarray