ก่อนอื่น (แม้ว่าจะไม่เปลี่ยนแปลงประสิทธิภาพเลยก็ตาม) ให้พิจารณาทำความสะอาดโค้ดของคุณคล้ายกับสิ่งนี้:
import matplotlib.pyplot as plt
import numpy as np
import time
x = np.arange(0, 2*np.pi, 0.01)
y = np.sin(x)
fig, axes = plt.subplots(nrows=6)
styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-']
lines = [ax.plot(x, y, style)[0] for ax, style in zip(axes, styles)]
fig.show()
tstart = time.time()
for i in xrange(1, 20):
for j, line in enumerate(lines, start=1):
line.set_ydata(np.sin(j*x + i/10.0))
fig.canvas.draw()
print 'FPS:' , 20/(time.time()-tstart)
จากตัวอย่างข้างต้นฉันได้รับประมาณ 10fps
เพียงบันทึกสั้น ๆ ขึ้นอยู่กับกรณีการใช้งานที่แน่นอนของคุณ matplotlib อาจไม่ใช่ทางเลือกที่ดี มุ่งเน้นไปที่ตัวเลขคุณภาพการตีพิมพ์ไม่ใช่การแสดงผลแบบเรียลไทม์
อย่างไรก็ตามมีหลายสิ่งที่คุณสามารถทำได้เพื่อเร่งตัวอย่างนี้
มีสาเหตุหลักสองประการที่ทำให้สิ่งนี้ช้าอย่างที่เป็นอยู่
1) การโทรfig.canvas.draw()
วาดทุกอย่างใหม่ มันเป็นคอขวดของคุณ ในกรณีของคุณคุณไม่จำเป็นต้องวาดสิ่งต่างๆใหม่เช่นขอบเขตแกนป้ายกำกับ ฯลฯ
2) ในกรณีของคุณมีพล็อตย่อยจำนวนมากที่มีป้ายกำกับเครื่องหมายถูกจำนวนมาก สิ่งเหล่านี้ใช้เวลาวาดนาน
ทั้งสองอย่างนี้สามารถแก้ไขได้โดยใช้ blitting
ในการทำ blitting อย่างมีประสิทธิภาพคุณจะต้องใช้รหัสเฉพาะแบ็กเอนด์ ในทางปฏิบัติหากคุณกังวลจริงๆเกี่ยวกับภาพเคลื่อนไหวที่ราบรื่นคุณมักจะฝังแผนภาพ matplotlib ไว้ในชุดเครื่องมือ gui บางประเภทดังนั้นนี่จึงไม่ใช่ปัญหามากนัก
อย่างไรก็ตามหากไม่รู้อีกเล็กน้อยว่าคุณกำลังทำอะไรอยู่ฉันไม่สามารถช่วยคุณได้
อย่างไรก็ตามมีวิธีการทำแบบ Gui-neutral ที่ยังเร็วพอสมควร
import matplotlib.pyplot as plt
import numpy as np
import time
x = np.arange(0, 2*np.pi, 0.1)
y = np.sin(x)
fig, axes = plt.subplots(nrows=6)
fig.show()
fig.canvas.draw()
styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-']
def plot(ax, style):
return ax.plot(x, y, style, animated=True)[0]
lines = [plot(ax, style) for ax, style in zip(axes, styles)]
backgrounds = [fig.canvas.copy_from_bbox(ax.bbox) for ax in axes]
tstart = time.time()
for i in xrange(1, 2000):
items = enumerate(zip(lines, axes, backgrounds), start=1)
for j, (line, ax, background) in items:
fig.canvas.restore_region(background)
line.set_ydata(np.sin(j*x + i/10.0))
ax.draw_artist(line)
fig.canvas.blit(ax.bbox)
print 'FPS:' , 2000/(time.time()-tstart)
สิ่งนี้ให้ฉัน ~ 200fps
เพื่อให้สะดวกยิ่งขึ้นมีanimations
โมดูลใน matplotlib เวอร์ชันล่าสุด
ตัวอย่างเช่น:
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
x = np.arange(0, 2*np.pi, 0.1)
y = np.sin(x)
fig, axes = plt.subplots(nrows=6)
styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-']
def plot(ax, style):
return ax.plot(x, y, style, animated=True)[0]
lines = [plot(ax, style) for ax, style in zip(axes, styles)]
def animate(i):
for j, line in enumerate(lines, start=1):
line.set_ydata(np.sin(j*x + i/10.0))
return lines
ani = animation.FuncAnimation(fig, animate, xrange(1, 200),
interval=0, blit=True)
plt.show()