提速matplotlib散点图

2024-05-13 23:44:50 发布

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

我正在尝试制作一个交互式程序,它主要使用matplotlib绘制大量点(10k-100k左右)的散点图。现在它可以工作,但是更改需要很长时间才能呈现。少量的分数是可以的,但是一旦分数上升,事情就会很快变得令人沮丧。所以,我正在研究加速分散的方法,但我运气不太好

有一种显而易见的方法(现在的实现方式) (我意识到情节重画没有更新。我不想用大量随机调用来改变fps结果)。

import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
import time


X = np.random.randn(10000)  #x pos
Y = np.random.randn(10000)  #y pos
C = np.random.random(10000) #will be color
S = (1+np.random.randn(10000)**2)*3 #size

#build the colors from a color map
colors = mpl.cm.jet(C)
#there are easier ways to do static alpha, but this allows 
#per point alpha later on.
colors[:,3] = 0.1

fig, ax = plt.subplots()

fig.show()
background = fig.canvas.copy_from_bbox(ax.bbox)

#this makes the base collection
coll = ax.scatter(X,Y,facecolor=colors, s=S, edgecolor='None',marker='D')

fig.canvas.draw()

sTime = time.time()
for i in range(10):
    print i
    #don't change anything, but redraw the plot
    ax.cla()
    coll = ax.scatter(X,Y,facecolor=colors, s=S, edgecolor='None',marker='D')
    fig.canvas.draw()
print '%2.1f FPS'%( (time.time()-sTime)/10 )

速度达到每秒0.7帧

或者,我可以编辑散点返回的集合。为此,我可以改变颜色和位置,但不知道如何改变每个点的大小。我想应该是这样的

import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
import time


X = np.random.randn(10000)  #x pos
Y = np.random.randn(10000)  #y pos
C = np.random.random(10000) #will be color
S = (1+np.random.randn(10000)**2)*3 #size

#build the colors from a color map
colors = mpl.cm.jet(C)
#there are easier ways to do static alpha, but this allows 
#per point alpha later on.
colors[:,3] = 0.1

fig, ax = plt.subplots()

fig.show()
background = fig.canvas.copy_from_bbox(ax.bbox)

#this makes the base collection
coll = ax.scatter(X,Y,facecolor=colors, s=S, edgecolor='None', marker='D')

fig.canvas.draw()

sTime = time.time()
for i in range(10):
    print i
    #don't change anything, but redraw the plot
    coll.set_facecolors(colors)
    coll.set_offsets( np.array([X,Y]).T )
    #for starters lets not change anything!
    fig.canvas.restore_region(background)
    ax.draw_artist(coll)
    fig.canvas.blit(ax.bbox)
print '%2.1f FPS'%( (time.time()-sTime)/10 )

这将导致0.7 fps的速度变慢。我想尝试使用CircleCollection或RegularPolygonCollection,因为这样可以很容易地更改大小,而且我不在乎更改标记。但是,我两个都画不出来,所以我不知道他们会不会画得更快。所以,现在我在找主意。


Tags: theimporttimematplotlibasnpfigplt
2条回答

我们正在积极研究大型matplotlib散点图的性能。 我鼓励你参与到对话中来(http://matplotlib.1069221.n5.nabble.com/mpl-1-2-1-Speedup-code-by-removing-startswith-calls-and-some-for-loops-td41767.html),更好的是,测试已经提交的pull请求,让类似的案例(https://github.com/matplotlib/matplotlib/pull/2156)的生活变得更好。

高温高压

我已经试过几次了,试着用大量的点来加速散点图的绘制,尝试了不同的方法:

  • 不同的标记类型
  • 限制颜色
  • 缩减数据集
  • 使用热图/网格而不是散点图

这些都不管用。Matplotlib在散点图方面的性能不是很好。我唯一的建议是使用一个不同的绘图库,尽管我个人还没有找到一个合适的。我知道这没有多大帮助,但它可能会帮你省下几个小时毫无结果的修补工作。

相关问题 更多 >