提高matplotlib对数据子集的性能

时间:2016-12-22 09:02:34

标签: python matplotlib pyqt4

我有一个小的PyQT4应用程序,它显示了一个大数据集(100k点×14个通道)的图。我只想显示128点的时间段并点击以显示下一个时段。

我天真的方法是创建数字,并在循环中的每个步骤中仅绘制我的数据的子集。这导致加载时间相当长一段时间,我认为这可能对此任务有很大帮助。

有什么方法可以提高性能吗?我是否错过了一些matplotlib内置函数来仅绘制数据子集?我不介意在应用程序开始时加载时间更长,所以也许我可以将它全部绘制并放大?

编辑:提供了一个简单的运行示例

我机器上的

Took 7.39s to plot 8 samples

导入时间

import matplotlib.pyplot as plt
import numpy as np


plt.ion()

num_channels = 14
num_samples = 1024

data = np.random.rand(num_channels, num_samples)

figure = plt.figure()

start = 0
period = 128

axes = []
for i in range(num_channels):
    axes.append(figure.add_subplot(num_channels, 1, i+1))

end = start+period
x_values = [x for x in range(start, end)]

begin = time.time()
num_plot = 0
for i in range(0, num_samples, period):
    num_plot += 1
    end = start+period

    for i, ax in enumerate(axes):
        ax.hold(False)
        ax.plot(x_values, data[i][start:end], '-')
        ax.set_ylabel(i)
    start += period

    figure.canvas.draw()
print("Took %.2fs to plot %d samples" % (time.time()-begin, num_plot))

1 个答案:

答案 0 :(得分:0)

从这里使用@ joe-kington答案:How to update a plot in matplotlib将性能提升到合适的价值。

我现在只使用set_ydata()更改线对象的y值。 调用ax.plot()时只返回一次调用行对象。

编辑:添加了一个正在运行的示例: 我机器上的Took 3.11s to plot 8 samples

import time

import matplotlib.pyplot as plt
import numpy as np


plt.ion()

num_channels = 14
num_samples = 1024

data = np.random.rand(num_channels, num_samples)

figure = plt.figure()

start = 0
period = 128

axes = []
for i in range(num_channels):
    axes.append(figure.add_subplot(num_channels, 1, i+1))

end = start+period
x_values = [x for x in range(start, end)]

lines = []
begin = time.time()
num_plot = 1 # first plot
for i, ax in enumerate(axes):
    ax.hold(False)

    # save the line object
    line, = ax.plot(x_values, data[i][start:end], '-')
    lines.append(line)

    ax.set_xlim([start,end])
    ax.set_ylabel(i)

start += period
for _ in range(period, num_samples, period):
    num_plot += 1
    end = start + period
    for i, line in enumerate(lines):
        line.set_ydata(data[i][start:end])
    start += period

    figure.canvas.draw()
print("Took %.2fs to plot %d samples" % (time.time()-begin, num_plot))