Updating the positions and colors of pyplot.scatter

老子叫甜甜 提交于 2019-12-10 17:32:58

问题


I have been struggling with this for a while and can't get it to work. I am reading a file in chunks and scatter plotting data from it, and I would like to "animate" it by updating the scatter plot for each chunk in a for loop (and also adapt it to a live stream of data).

So something like this ugly example works for a single plot:

x = [1, 2, 3, 4]
y = [4, 3, 2, 1]
alpha = [0.2, 0.3, 0.8, 1.0]
c = np.asarray([(0, 0, 1, a) for a in alpha])
s = scatter(x, y, marker='o', color=c, edgecolors=c)

But how do I update the plot without calling s.remove() and scatter() repeatedly? The completely unintuitively-named s.set_array and s.set_offsets are supposed to update the colors and the x and y positions, but I can't figure out how to use them with the type of x, y, alpha data I have above.

(Also, is there a better way to do the alpha in the above plot?)


回答1:


The solution I found for this involves using Normalize to make a normalised colour list based on the relevant data, mapping it to a ScalarMappable, and using that to set the face colour and c limits on each frame of the animation. With scat the handle of the scatter plot and speedsList provides the colour data:

n = mpl.colors.Normalize(vmin = min(speedsList), vmax = max(speedsList))
m = mpl.cm.ScalarMappable(norm=n, cmap=mpl.cm.afmhot)
scat.set_facecolor(m.to_rgba(speedsList))
scat.set_clim(vmin=min(speedsList), vmax=max(speedsList))

This does exactly what I expect it to.



来源:https://stackoverflow.com/questions/23966121/updating-the-positions-and-colors-of-pyplot-scatter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!