当数据每秒追加到列表中时,如何在 matplotlib 上实时绘制简单的折线图? [英] How to plot simple line graph on matplotlib in real time when data is appending every second in list?

查看:35
本文介绍了当数据每秒追加到列表中时,如何在 matplotlib 上实时绘制简单的折线图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个 API,它返回一个字典,其中包含一个键,该键的值每秒钟都在变化.

这是

I am using an API which returns a dictionary containing a key whose value keeps changing every second.

This is the API call link which returns the data in this form.

{"symbol":"ETHUSDT","price":"588.15000000"}

Here.. the key "price" keeps changing its value every second.

This is my Python scrips which appends this value in a list.

import requests
import matplotlib.pyplot as plt


url = "https://api.binance.com/api/v3/ticker/price?symbol=ETHUSDT"

def get_latest_crypto_price():
  
  r = requests.get(url)
  response_dict = r.json()
  
  return float(response_dict['price'])


def main():
  
  last_price = 10
  
  eth_price =[]
  
  while True:
      price = get_latest_crypto_price()
      if price != last_price:
          eth_price.append(price)
          
          fig, ax = plt.subplots()
          ax.plot(eth_price)
          plt.show()

          last_price = price
      
     
main()            
       
        
      
      



    
    

        

My Question?

My code does plot the line but every time I have to close the Plot Window and it reopens again showing the new appended value. I know this is happening because my loop starts again after appending each value.

I am struck as to how to plot this in real time. Kindly help me in correcting my script.

Thank You

解决方案

Animation sets up the basic shape of the graph you want to animate, and then displays it by repeatedly assigning it to the line graph with the animation function. This example shows adding a value to the y-axis and getting a value in a slice and displaying it. 30 frames at 1 second intervals are drawn. You can understand the animation if you check the behavior of the animation while modifying the parameters. I'm in a jupyterlab environment so I have several libraries in place. I have also introduced another library for creating GIF images.

import requests
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from IPython.display import HTML # for jupyter lab
from matplotlib.animation import PillowWriter # Create GIF animation

url = "https://api.binance.com/api/v3/ticker/price?symbol=ETHUSDT"

eth_price =[]
last_price = 10

x = np.arange(31)

fig = plt.figure()
ax = plt.axes(xlim=(0, 31), ylim=(580, 600))
line, = ax.plot([], [], 'r-', marker='.', lw=2)

def ani_plot(i):
    r = requests.get(url)
    response_dict = r.json()
    price = float(response_dict['price'])
    if price != last_price:
        eth_price.append(price)
    line.set_data(x[:i], eth_price[:i])
#     print(price)
    return line,

anim = FuncAnimation(fig, ani_plot, frames=31, interval=1000, repeat=False)

plt.show()
anim.save('realtime_plot_ani.gif', writer='pillow')

# jupyter lab 
#plt.close()
#HTML(anim.to_html5_video())

这篇关于当数据每秒追加到列表中时,如何在 matplotlib 上实时绘制简单的折线图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆