2017-09-27 6 views
-1

현재 Walabot 장치에서 3D-rawdata를 시각화하여 matplotlib FuncAnimation으로 만든 3D 애니메이션으로 표시하려고합니다. 이미 답변을 검색했지만 도움이되는 정보를 찾을 수 없습니다. 필자의 경우 이미 3 차원 배열을 가지고 있는데, 각 인덱스는 시간에 따라 변하는 특정 값을 가지고 있습니다. 이미 다른 색상과 크기로 3D 차트에 표시하는 방법을 알 수 있었지만 이제는 업데이트 자체를 만들고 싶습니다. 나에게 좋은 시작을 제공하는 몇 가지 예제 코드를 발견했지만 내 차트는 독자적으로 업데이트되지 않습니다. 창을 닫아야하고 3D 배열과 다른 값으로 창이 다시 나타납니다. 이 문제를 해결하는 방법을 알고 계십니까? 여기에 지금까지 내 코드입니다 : 당신이Python의 3D 배열 값 Matplotlib 애니메이션

ani = anim.FuncAnimation(fig, update(ax, signal, plt), frames=10 , blit=True, repeat = True) 

상단에서 업데이트 기능을 필요로 행을 볼 수 있듯이

def update(plot, signal, figure): 
    plot.clear() 
    scatterplot = plot.scatter(x, y, z, zdir='z', s=signal[0], c=signal[0]) 
    figure.show() 
    return figure 

def calc_RasterImage(signal): 
    # 3D index is represnted is the following schema {i,j,k} 
    # sizeX - signal[1] represents the i dimension length 
    # sizeY - signal[2] represents the j dimension length 
    # sizeZ - signal[3] represents the k dimension length 
    # signal[0][i][j][k] - represents the walabot 3D scanned image (internal data) 

    #Initialize 3Dplot with matplotlib      
    fig = plt.figure() 
    ax = fig.add_subplot(111, projection='3d') 
    ax.set_xlim([xMin-1,xMax-1]) 
    ax.set_ylim([yMin-1,yMax-1]) 
    ax.set_zlim([zMin-1,zMax-1]) 
    ax.set_xlabel('X AXIS') 
    ax.set_ylabel('Y AXIS') 
    ax.set_zlabel('Z AXIS') 
    scatterplot = ax.scatter(x, y, z, zdir='z', s=signal[0], c= signal[0]) 
    cbar = plt.colorbar(scatterplot) 
    cbar.set_label('Density') 
    #def update(signal): 
    #  ax.clear() 
    #  scatterplot = ax.scatter(x, y, z, zdir='z', s=signal[0], c=signal[0]) 
    ani = anim.FuncAnimation(fig, update(ax, signal, plt), frames=10 , blit=True, repeat = True) 

def main(): 
    wlbt = Walabot() 
    wlbt.connect() 
    if not wlbt.isConnected: 
      print("Not Connected") 
    else: 
      print("Connected") 
    wlbt.start() 
    calc_index(wlbt.get_RawImage_values()) 
    while True: 
      #print_RawImage_values(wlbt.get_RawImage_values()) 
      calc_RasterImage(wlbt.get_RawImage_values()) 
    wlbt.stop() 

if __name__ == '__main__': 
    main() 

은. 이 함수는 내 플롯을 지우고 다른 값을 가진 새로운 플롯을 다시 만듭니다. 하지만 항상 먼저 줄거리 창을 닫아야합니다. 나는 그것을 피하고 싶습니다. 다음은 플롯의 모양입니다. 3D array plot with matplotlib scatter 이 문제를 해결하는 방법에 대해 알고 계십니까?

환호

답변

0

귀하의 코드는 정말 최소한의 작업 예를하지 않고, 당신이 게으른 실제로 SO에 오기 전에 FuncAnimation에 대한 문서를 읽을해야합니다. 즉, 이런 식으로 작동해야합니다 :

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 

""" 
Display walabot output. 
""" 

import matplotlib.pyplot as plt 
from matplotlib.animation import FuncAnimation 

def display(walabot_instance): 

    # set x, y, z 

    fig = plt.figure() 
    ax = fig.add_subplot(111, projection='3d') 
    path_collection = ax.scatter(x, y, z, zdir='z') 

    # do your labelling, layout etc 

    def update(ignored, walabot_instance): 
     signal = walabot_instance.get_RawImage_values() 
     path_collection.set_sizes(signal[0]) 
     path_collection.set_color(signal[1]) 
     return path_collection, 

    return FuncAnimation(fig, update, fargs=[walabot_instance]) 

def main(): 
    wlbt = Walabot() 
    wlbt.connect() 
    if not wlbt.isConnected: 
     print("Not Connected") 
    else: 
     print("Connected") 
    wlbt.start() 

    plt.ion() 
    animation = display(wlbt) 
    raw_input("Press any key when done watching Walabot...") 


if __name__ == "__main__": 
    main() 

질문이있는 경우 (문서를 읽은 후!) 코멘트를 드롭하십시오.

+0

누락 된 mcve를 비판하고 여전히 답을 제공하는 것은 다소 모순 된 것처럼 보이지만 그 자체로는 설명이 없습니다. 나는 질문의 분명한 분명한 점을 질문자에게 상기시켜야한다고 생각한다. 다른 한편으로는 질문에 대답 할 수 있다면, 왜 MCU가 누락 된 것에 대해 귀찮게합니까? 또는 그 반대의 경우 : 질문이 명확하지 않은 경우 왜 대답을 제공합니까?어쨌든 코드 조각을 던지고 "이해하고 싶다면 문서를 읽으십시오"라고 똑같이 나쁘다. – ImportanceOfBeingErnest

+0

@ImportanceOfBeingErnest 나는 그에게 _first_ 문서를 읽고 나머지 질문을 요청했다. 나는 실제로 말했던 것과 당신이 그것을 어떻게 묘사하고 있는지간에 차이가 있다고 주장 할 것이다. – Paul

0

도움 주셔서 감사합니다. 코드를 시험해보고 광산에 맞추어 마침내 성공했습니다. 나는 문서 (https://matplotlib.org/api/_as_gen/matplotlib.animation.FuncAnimation.html#matplotlib.animation.FuncAnimation)를보고 있었지만 올바르게 코딩하는 방법이 없기 때문에 올바르게 사용하는 방법을 찾지 못했습니다. 어쨌든 여기에 나의 새로운 코드는 다음과 같습니다

def calc_index(signal): 
    for i in range(0, signal[1], 1): 
      for j in range(0, signal[2], 1): 
        for k in range(0, signal[3], 1): 
          #Location of Index 
          x.append(i) 
          y.append(j) 
          z.append(k) 

def display(walabot_instance): 
    # 3D index is represnted is the following schema {i,j,k} 
    # sizeX - signal[1] represents the i dimension length 
    # sizeY - signal[2] represents the j dimension length 
    # sizeZ - signal[3] represents the k dimension length 
    # signal[0][i][j][k] - represents the walabot 3D scanned image (internal data) 

    #Initialize 3Dplot with matplotlib      
    fig = plt.figure() 
    ax = fig.add_subplot(111, projection='3d') 
    signal = walabot_instance.get_RawImage_values() 
    path_collection = ax.scatter(x, y, z, zdir='z', s=signal[0], c=signal[0]) 

    #Plot labeling 
    ax.set_xlim([xMin-1,xMax-1]) 
    ax.set_ylim([yMin-1,yMax-1]) 
    ax.set_zlim([zMin-1,zMax-1]) 
    ax.set_xlabel('X AXIS') 
    ax.set_ylabel('Y AXIS') 
    ax.set_zlabel('Z AXIS') 
    cbar = plt.colorbar(path_collection) 
    cbar.set_label('Density') 

    def update(ignored, walabot_instance): 
      ax.clear() 
      signal_update = walabot_instance.get_RawImage_values() 
      path_collection = ax.scatter(x, y, z, zdir='z', s=signal_update[0], c=signal_update[0]) 
      return path_collection 

    return FuncAnimation(fig, update, fargs=[walabot_instance]) 

def main(): 
    wlbt = Walabot() 
    wlbt.connect() 
    if not wlbt.isConnected: 
      print("Not Connected") 
    else: 
      print("Connected") 
    wlbt.start() 

    calc_index(wlbt.get_RawImage_values()) 
    plt.ion() 
    animation = display(wlbt) 

    raw_input("Press any key when done watching Walabot...") 
    wlbt.stop() 

if __name__ == '__main__': 
    main() 

내가 아직도 당신의 FuncAnimation 함수에서

fargs=[walabot_instance] 

를 무엇을 사용하고있다 이해하지? 난 그냥이 .. 문서를 얻을하지 않습니다 그리고 무슨 일이

def func(fr: object, *fargs) -> iterable_of_artists: 

과 FUNC 및 프레임 매개 변수에 대한 FuncAnimation 설명서

def gen_function() -> obj: 

을 의미? 이 과정을 더 잘 이해하기 만하면됩니다.

왜 업데이트에 무시 된 매개 변수 입력이 필요합니까? 그것은 어디에도 사용되지 않습니다 ..

고마워!

+0

'FuncAnimation'은 사용 사례를 위해 설계되지 않았습니다. 의도 한 유스 케이스의 경우 동적 인 시스템의 진화를 묘사 한 것은 이미 의 모든 데이터를 가지고 있거나 시간의 함수로 시스템의 상태를 설명하는 함수를 알고 있기 때문에 결정적입니다. 따라서 update는 시간을 나타내는 float 또는 정수를 기대하며 이는 시스템의 새 상태 또는 생성자 함수 또는 데이터 자체의 형태로 새 상태를 파악하는 데 사용할 수 있습니다. – Paul

+0

귀하의 경우 시스템의 새로운 상태는 런타임이 입니다. 이 발전기와 비슷해 보이지만 그게 지나치게 인 것처럼 보입니다. 그러므로'frame' 인수는 불필요하므로 무시합니다. – Paul

+0

'fargs'는 업데이트 함수에 추가 매개 변수를 전달하는 데 사용됩니다. 코드를 보면 방금 전달하지 않아도된다는 것을 알았습니다. (원래는 'update' 함수를 클로저로 설계하지 않았습니다.이 경우에는 walabot 인스턴스가 범위에 포함되지 않았을 것입니다. 당신이 그것을 필요로했다). – Paul