2

我想使用 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(...) 但没有出现窗口

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

4

1 回答 1

0

你应该看看matplotlib.animation.FuncAnimation这是基于此示例的如何使用它的原型。

#!/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]])
    plt.cla()
    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)
于 2013-11-03T10:57:32.687 回答