如何在python中使用matplotlib通过for循环创建多个视图



我需要在python中使用matplotlib制作100个视图。起点总是随机的。我知道如何生成100个图,但我想使用";"前进到下一个视图";箭头。

这是我的代码:

import matplotlib.pyplot as plt

for i in range (1,3):
Startx = [randrange(1, 19)]  # x axis values
Starty = [randrange(1, 8)]  # y axis values
plt.plot(Startx, Starty, color='black', linestyle='solid', linewidth=3,  # plotting the points
marker='o', markerfacecolor='green', markersize=8)
##########################################################################################################
Endx = [16.5]
Endy = [7.5]
plt.plot(Endx, Endy, color='black', linestyle='solid', linewidth=3,
marker='o', markerfacecolor='red', markersize=8)
##########################################################################################################
Ax = [5, 2.5, 3, 5, 6, 5]
Ay = [7.5, 6, 3.5, 3, 5.5, 7.5]
plt.plot(Ax, Ay, color='black', linestyle='solid', linewidth=3,
marker='o', markerfacecolor='blue', markersize=8)
##########################################################################################################
Bx = [8, 6.5, 7.25, 8]
By = [3, 3, 5.5, 3]
plt.plot(Bx, By, color='black', linestyle='solid', linewidth=3,
marker='o', markerfacecolor='blue', markersize=8)
plt.xlim(0, 19)
plt.ylim(0, 8)  # setting x and y axis range
plt.xlabel('x - axis')  # naming the x axis
plt.ylabel('y - axis')  # naming the y axis
plt.show()  # function to show the plot

您可以尝试本文中提到的这种方法matplotlib挂接主页/后退/前进按钮事件使用"前进"按钮,而不是覆盖"主页"按钮。

也可以看看这个小例子。每次按下"前进到下一个视图"按钮,绘图都会更新一些随机数据。

from matplotlib.backends.backend_tkagg import NavigationToolbar2Tk
import matplotlib.pyplot as plt
from random import randint
#new forward button callback => gets triggered, when forward button gets pushed
def customForward(*args):
ax = plt.gca()
fig = plt.gcf()

#get line object...
line = ax.get_lines()[0]

#...create some new random data...
newData = [randint(1, 10), randint(1, 10), randint(1, 10)]

#...and update displayed data
line.set_ydata(newData)
ax.set_ylim(min(newData), max(newData))
#redraw canvas or new data won't be displayed
fig.canvas.draw()
#monkey patch forward button callback
NavigationToolbar2Tk.forward = customForward
#plot first data
plt.plot([1, 2, 3], [1, 2, 3])
plt.show()

最新更新