How to plotting online with pyplot?

2019-07-30 07:31发布

问题:

I have a python program like this:

import matplotlib.pyplot as plt

p = []
for i in range(1000):
    p.append(i)
    plt.plot(p)

p Is a list of numbers that will grow in every iteration. So I like to see plotting result in every iteration, but it shows me the result after 1000 iterations! How can I fix it?

EDIT:

I tried to edit my code and using the suggested solution but didn't work and my code runs like before:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
import requests
import numpy as np

ask_volumes = []
bid_volumes = []
first_price = []
last_prices = []

fig, ax = plt.subplots()
y = []

for i in range(2600):

    time.sleep(1)
    codes = ['OSFKH98', 'OSFOR98','OSFTR98', 'SAFKH98','SAFOR98','SAFTR98']
    all_data = []
    with requests.Session() as s:
        for code in codes:
               data = {'ContractCode' : code}
               r = s.post('http://cdn.ime.co.ir/Services/Fut_Live_Loc_Service.asmx/GetContractInfo', json = data ).json()
               #print(r)




    for key, value in r.items():
        print(r[key]['ContractCode'])
        ask_volumes.append( (r[key]['AskVolume1']) + (r[key]['AskVolume2']) + (r[key]['AskVolume3']) + (r[key]['AskVolume4']) + (r[key]['AskVolume5']) )
        bid_volumes.append( (r[key]['BidVolume1']) + (r[key]['BidVolume2']) + (r[key]['BidVolume3']) + (r[key]['BidVolume4']) + (r[key]['BidVolume5']) )
        first_price = (r[key]['FirstTradedPrice'])
        last_prices = (r[key]['LastTradedPrice'])

        y.append(last_prices)
        x = np.arange(0,i+1,1)
        line, = ax.plot(x, y)




    def animate(num, x, y, line):
        line.set_data(x[:num], y[:num])
        return line,

    ani = animation.FuncAnimation(fig, animate, fargs=[x, y, line],
                          interval=1, blit=True)
    plt.show()

回答1:

Based on the answer to this question:

import numpy as np
import matplotlib.pyplot as plt

plt.ion()
plt.show()
p = []
for i in range(10):
    p+=[i]
    plt.plot(p)
    plt.pause(0.5)

For me it worked fine, hope it helps.



回答2:

Something like this?

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

x = np.arange(0, 1000, 1)
y = x

fig, ax = plt.subplots()
line, = ax.plot(x, y)

def animate(num, x, y, line):
    line.set_data(x[:num], y[:num])
    return line,

ani = animation.FuncAnimation(fig, animate, fargs=[x, y, line],
                          interval=1, blit=True)
plt.show()