在同一图上使用Python和Matplotlib显示实时烛台

时间:2013-11-03 10:42:04

标签: python animation matplotlib

我想使用Python和Matplotlib显示实时烛台图表

我做了这个

#!/usr/bin/env python

import time
import matplotlib.pyplot as plt

from matplotlib.pyplot import plot, draw, show
from matplotlib.finance import candlestick
from matplotlib.dates import date2num

from numpy import nan
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

#plt.ion()
#plt.ioff()

while True:

    #plt.clf()

    #ax = plt.gca()

    opn =  104.04852126730329
    close = np.random.uniform(90, 110)
    high = max(opn, close)*np.random.uniform(1, 1.05)
    low = min(opn, close)*np.random.uniform(0.95, 1)
    DOCHLV = [[1, 100, 99, 101, 98, 0.0], [2, nan, nan, nan, nan, 0.0], [3, nan, nan, nan, nan, 0.0], [4, 104, 98, 105, 95, 0.0], [5, nan, nan, nan, nan, 0.0], [6, nan, nan, nan, nan, 0.0], [7, 100, 99.99976844819628, 100.91110690369828, 97.82248296015564, 1152.3258524820196], [8, 99.99976844819628, 100.51985544064271, 100.51985544064271, 96.65206230438159, 1578.5836411214814], [9, 100.51985544064271, 104.04852126730329, 104.54571702827914, 99.49632496479201, 1477.5651279091041], [10, opn, close, high, low, 372.6679262982206]]
    print(DOCHLV)

    #plt.close()

    fig = plt.figure()
    ax = fig.add_subplot(111)

    _ = candlestick(ax, DOCHLV, width=0.8, colorup='g', colordown='r', alpha=1.0)
    _ = ax.set_xlim(0, len(DOCHLV)+1)  

    #plt.show()
    plt.show(block=False)

    time.sleep(0.5)

不幸的是,蜡烛画在几个数字上。

有没有办法解决这个问题?

我试图删除

    fig = plt.figure()
    ax = fig.add_subplot(111)
来自while循环的

(为了在相同的斧头上绘图) 但图表未更新

我也尝试使用plt.draw()而不是plt.show(...) 但窗口没有出现

我还试图在绘制之前关闭(上一个)窗口...但是 在这种情况下,图表闪烁。

1 个答案:

答案 0 :(得分:0)

你应该看看matplotlib.animation.FuncAnimation。以下是您可以使用它的原型based on this example

#!/usr/bin/env python
from numpy import nan
import numpy as np

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

fig = plt.figure()
ax = fig.add_subplot(111)

def test(dummy):
    opn =  104.04852126730329
    close = np.random.uniform(90, 110)
    high = max(opn, close)*np.random.uniform(1, 1.05)
    low = min(opn, close)*np.random.uniform(0.95, 1)
    DOCHLV = np.array([[1, 100, 99, 101, 98, 0.0], [2, nan, nan, nan, nan, 0.0], [3, nan, nan, nan, nan, 0.0], [4, 104, 98, 105, 95, 0.0], [5, nan, nan, nan, nan, 0.0], [6, nan, nan, nan, nan, 0.0], [7, 100, 99.99976844819628, 100.91110690369828, 97.82248296015564, 1152.3258524820196], [8, 99.99976844819628, 100.51985544064271, 100.51985544064271, 96.65206230438159, 1578.5836411214814], [9, 100.51985544064271, 104.04852126730329, 104.54571702827914, 99.49632496479201, 1477.5651279091041], [10, opn, close, high, low, 372.6679262982206]])
    candlestick(ax, DOCHLV, width=0.8, colorup='g', colordown='r', alpha=1.0)
    ax.set_xlim(0, len(DOCHLV)+1)
anim = FuncAnimation(fig, test, interval=25)
anim.save('teste.mp4', fps=15)