首页 > 解决方案 > 将实时条形图与折线图一起绘制

问题描述

我有一个 csv 文件,可以在开市时实时更新两只股票的数据。我有一些代码(从互联网上找到的样本)在两个子图中绘制了两只股票的买价和卖价。该程序运行良好,它看起来像:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib.gridspec as gridspec

gs = gridspec.GridSpec(ncols=1, nrows=2)
ax2 = plt.subplot(gs[1])
plt.plot([], [])
plt.plot([], [])
ax1 = plt.subplot(gs[0], sharex=ax2)
plt.plot([], [])
plt.plot([], [])

def animate(i):
    data = pd.read_csv(r'C:\Users\...\Desktop\test\stock_data.csv')
    x = data.index
    y1 = data.bid_p_x
    y2 = data.ask_p_x
    y3 = data.bid_p_y
    y4 = data.ask_p_y

    line1, line2 = ax1.lines
    line1.set_data(x, y1)
    line2.set_data(x, y2)
    line3, line4 = ax2.lines
    line3.set_data(x, y3)
    line4.set_data(x, y4)

ani = FuncAnimation(plt.gcf(), animate, interval=250)
ax1.grid(True)
ax2.grid(True)
plt.tight_layout()
plt.show()

我选择此代码的原因是因为我可以在图表每 0.25 秒更新一次时自由放大图表上的任何位置(而不是每次图表更新时框架都会变回默认值)。

但是,当我尝试将实时条形图与实时线图(即一只股票价格的线图和交易量的条形图)一起绘制时,我遇到了一些错误。所以我plt.plot([], [])改为plt.bar([], [])ax2 = plt.subplot(gs[1])

...
gs = gridspec.GridSpec(ncols=1, nrows=2)
ax2 = plt.subplot(gs[1])
plt.bar([], [])
plt.bar([], [])
ax1 = plt.subplot(gs[0], sharex=ax2)
plt.plot([], [])
plt.plot([], [])

def animate(i):
    data = pd.read_csv(r'C:\Users\...\Desktop\test\stock_data.csv')

    x = data.index
    y1 = data.price_x
    y2 = data.last_volume_x

    line1, line2 = ax1.lines
    line1.set_data(x, y1)
    line3, line4 = ax2.lines
    line3.set_data(x, y2)

ani = FuncAnimation(plt.gcf(), animate, interval=250)
ax1.grid(True)
ax2.grid(True)
plt.tight_layout()
plt.show()
...

我得到这个错误:line3, line4 = ax2.linesValueError: not enough values to unpack (expected 2, got 0)

我还尝试定义line1andline2之后ax1ax2被定义:

gs = gridspec.GridSpec(ncols=1, nrows=2)
ax2 = plt.subplot(gs[1])
line2, = plt.bar([], [])
ax1 = plt.subplot(gs[0], sharex=ax2)
line1, = plt.plot([], [])
plt.plot([], [])

def animate(i):
    data = pd.read_csv(r'C:\Users\...\Desktop\test\stock_data.csv')

    x = data.index
    y1 = data.price_x
    y2 = data.last_volume_x

    line1.set_data(x, y1)
    line2.set_data(x, y2)

ani = FuncAnimation(plt.gcf(), animate, interval=250)
ax1.grid(True)
ax2.grid(True)
plt.tight_layout()
plt.show()

我得到了同样的错误:line2, = plt.bar([], [])ValueError: not enough values to unpack (expected 1, got 0)

似乎 bar 与 plot 根本不同,我该如何解决这个问题?我唯一的要求仍然是我可以在地块上的任何地方导航,而地块正在更新。

标签: pythonmatplotlib

解决方案


推荐阅读