gpt4 book ai didi

python - 如何在 for 循环中向现有的 matplotlib 图形添加线条?

转载 作者:行者123 更新时间:2023-12-04 13:16:17 25 4
gpt4 key购买 nike

我对 matplotlib 不是很熟悉,想在 for 循环的每次迭代中为两个不同的绘图分别添加一条线。我尝试了下面简化示例中显示的两件事,但都抛出了错误。

import matplotlib.pyplot as plt

ax1 = plt.figure()
ax2 = plt.figure()

for i in range(5):
## these throw "Can not put single artist in more than one figure" error
plt.plot([0,i], [0,i], figure=ax1)
plt.plot([i,0], [i,0], figure=ax2)

## these throw "'Figure' object has no attribute 'plot'" error
ax1.plot([0,i], [0,i])
ax2.plot([i,0], [i,0])

最佳答案

我没有正确理解您的目标,但您收到了一个错误,因为您正在使用图形,就好像它们是轴一样。您需要声明一个属于图形的轴对象,如下所示:

import matplotlib.pyplot as plt

fig1 = plt.figure() #figure object
fig2 = plt.figure()
ax1 = fig1.gca() #axis object
ax2 = fig2.gca()

for i in range(5):
ax1.plot([0,i], [0,i])
ax2.plot([i,0], [i,0])

关于python - 如何在 for 循环中向现有的 matplotlib 图形添加线条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60153497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com