Python 将实时条形图与线图一起绘制

Python 将实时条形图与线图一起绘制,python,matplotlib,Python,Matplotlib,我有一个csv文件,在市场开盘时实时更新两支股票的数据。我有一些代码(从互联网上找到的样本),在两个子地块中绘制两支股票的出价和要价。该程序运行良好,看起来如下所示: import pandas as pd import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation import matplotlib.gridspec as gridspec gs = gridspec.GridSpec(ncol

我有一个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.25s更新一次时(而不是每次绘图更新时帧都会保持更改回默认值),我可以自由放大图形上的任何位置

然而,当我试图将实时条形图与实时折线图(即一只股票价格的折线图和交易量的条形图)一起绘制时,我得到了一些错误。因此,我将
ax2=plt.subplot(gs[1])
下的
plt.plot([],[])
更改为
plt.bar([],[])

我收到以下错误:
line3,line4=ax2。行
ValueError:没有足够的值来解包(预期为2,得到0)

在定义了
ax1
ax2
之后,我还尝试定义
line1
line2

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:没有足够的值来解包(预期为1,得到0)

从根本上看,条形图和绘图不同,我该如何解决这个问题?我唯一的要求仍然是,当绘图正在更新时,我可以在绘图上的任何位置导航

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()