簡體   English   中英

如何在matplotlib中更新pcolor?

[英]How to update pcolor in matplotlib?

我用pcolor從2D數組中繪制信息。 但是,數組中的信息在迭代過程中發生了變化,我想動態地更新顏色圖,以便實時看到變化。 我如何以最簡單的方式做到這一點?

編輯-示例:

from __future__ import division
from pylab import *
import random

n = 50 # number of iterations
x = arange(0, 10, 0.1)
y = arange(0, 10, 0.1)
T = zeros([100,100]) # 10/0.1 = 100
X,Y = meshgrid(x, y)

"""initial conditions"""
for x in range(100):
 for y in range(100):
  T[x][y] = random.random()

pcolor(X, Y, T, cmap=cm.hot, vmax=abs(T).max(), vmin=0)
colorbar()
axis([0,10,0,10])
show() # colormap of the initial array

"""main loop"""

for i in range(n):
 for x in range(100):
  for y in range(100):
   T[x][y] += 0.1 # here i do some calculations, the details are not important

 # here I want to update the color map with the new array (T)

謝謝

我建議使用imshowdoc ):

# figure set up
fig, ax_lst = plt.subplots(2, 1)
ax_lst = ax_lst.ravel()

#fake data
data = rand(512, 512)
x = np.linspace(0, 5, 512)
X, Y = meshgrid(x, x)

data2 = np.sin(X ** 2 + Y **2)
# plot the first time#fake data

im = ax_lst[0].imshow(data, interpolation='nearest', 
                            origin='bottom', 
                            aspect='auto', # get rid of this to have equal aspect
                            vmin=np.min(data),
                            vmax=np.max(data), 
                            cmap='jet')

cb = plt.colorbar(im)

pc = ax_lst[1].pcolor(data)
cb2 = plt.colorbar(pc)

要使用imshow更新數據,只需設置數據數組,它即可為您處理所有規范化和顏色映射:

# update_data (imshow)
im.set_data(data2) 
plt.draw()

要對pcolor做同樣的事情,您需要對自己進行歸一化和顏色映射(並猜對行主要vs列主要是正確的):

my_cmap = plt.get_cmap('jet')
#my_nom = # you will need to scale your read data between [0, 1]
new_color = my_cmap(data2.T.ravel())
pc.update({'facecolors':new_color})

draw() 

您可以將事件連接到圖形並在該事件上調用特定功能。 下面,我以matplotlib文檔為例,並添加了一個ontype函數。 在鍵盤上按1時將調用此選項。 然后調用X * func3() Ontype通過fig.canvas.mpl_connect('key_press_event',ontype)綁定到圖形。 以類似的方式,您可以觸發時間依賴的常規事件。

#!/usr/bin/env python
"""
See pcolor_demo2 for an alternative way of generating pcolor plots
using imshow that is likely faster for large grids
"""
from __future__ import division
from matplotlib.patches import Patch
from pylab import *

def ontype(event):
    ''' function that is called on key event (press '1')'''
    if event.key == '1':
        print 'It is working'
        fig.gca().clear()
        # plot new function X * func3(X, Y) 
        Z = X * func3(X, Y) 
        pcolor(X, Y, Z, cmap=cm.RdBu, vmax=abs(Z).max(), vmin=-abs(Z).max())
        fig.canvas.draw()

def func3(x,y):
    return (1- x/2 + x**5 + y**3)*exp(-x**2-y**2)


# make these smaller to increase the resolution
dx, dy = 0.05, 0.05

x = arange(-3.0, 3.0001, dx)
y = arange(-3.0, 3.0001, dy)
X,Y = meshgrid(x, y)

Z = func3(X, Y)

fig=figure(figsize=(16,8))

# connect ontype to canvas
fig.canvas.mpl_connect('key_press_event',ontype)

pcolor(X, Y, Z, cmap=cm.RdBu, vmax=abs(Z).max(), vmin=-abs(Z).max())
colorbar()
axis([-3,3,-3,3])

show()

我在這里有一個簡單的示例,該示例如何在仿真過程中更新ax.pcolor (或更確切地說,它是更快的表親ax.pcolormesh )。

def make_movie(fig, meshData, conc, fout='writer_test.mp4',
           dpi=150, metadata={}):
    '''
    Make a movie (on disk) starting from a first image generated with matplotlib,
    by updating only the values that were dispayed with ax.pcolormesh(...).

    Parameters
    ----------
    meshData: mesh as returned by ax.pcolormesh()
    conc: obj returned by readUCN
        computed concentrations
    fout: str
        name of output file, with or without '.mp4' extension.
    dpi: int
        dots per inch of output movie
    metadata: dict
        passed on to FFMpegWriter.savings(fout, ...)
    '''
    plt.rcParams['animation.ffmpeg_path'] = '/usr/local/bin/ffmpeg'

    from matplotlib.animation import FFMpegWriter

    writer = FFMpegWriter(fps=15, metadata=metadata)

    totims = conc.totim # get times of computed concentrations

    with writer.saving(fig, fout, dpi):
        for totim in totims:
            C = conc.at_t(totim)[:, 0, :] # 3D -->  2D Xsection concentrations
            #newcolors = cmap(norm(C.ravel()))
            #meshData.update({'facecolors': newcolors})
            meshData.update({'array': C.ravel()}) # reset array to new conc.
            fig.canvas.draw_idle()
            writer.grab_frame()

#newcolors#meshData.update開頭的行如上述#meshData.update所建議。 meshdata.udate({array ...開頭的行替換了它們。它只是更新數據而無需計算新的Facecolor。最后一種方法更簡單且同樣有效。不需要轉置數據數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM