2015-10-15 28 views
0

爲什麼當新數據通過數據流轉儲到「twitter-out」時,我的數據點會如此顯示?似乎它與動畫有關,因爲當我重新運行文件而沒有在新數據中進行流式傳輸時,它的繪圖就很好。繪圖數據在matplotlib中顯示錯誤

enter image description here

style.use('ggplot') 

fig = plt.figure() 
ax1 = fig.add_subplot(1, 1, 1) 

def animate(self): 

    pullData = open("twitter-out.txt", "r").read() 
    lines = pullData.split('\n') 

    xar = [] 
    yar = [] 

    x = 0 
    y = 0 

    for l in lines[:]: 
     x += 1 
     if "['pos']" in l: 
      y += 1 
     elif "['neg']" in l: 
      y -= 1 

     xar.append(x) 
     yar.append(y) 

    ax1.plot(xar, yar,color='r') 
    ax1.set_xlabel('Number of Tweets') 
    ax1.set_ylabel('Sentiment') 

ani = animation.FuncAnimation(fig, animate, interval=1000) 
plt.show() 

回答

0

修復1:

這主要的解決方法是非常簡單:只需添加ax1.cla()打電話之前ax1.plot()

說明:

的REA你看到的兒子是動畫在每次調用函數時都繪製一個新的繪圖,並將其疊加在所有先前的繪圖上。 所以你在你的問題中附上的數字實際上是來自animate調用的十幾個數字的疊加。 要解決這個問題,您只需使用清除軸命令ax.cla()清除軸中包含的以前的圖。

修復2:

的單槓在所有在那裏的原因是因爲你的dataPulled串總是以新的一行,在列表line結束變成了一個空字符串結束。 請參見例如:

>>> 'a\nb\n'.split('\n') 
['a', 'b', ''] 

所以你不得不削減這最後一在你for循環:

for l in lines[:-1]: