python - 将实时条形图与折线图一起绘制
问题描述
我有一个 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.lines
,ValueError: not enough values to unpack (expected 2, got 0)
。
我还尝试定义line1
andline2
之后ax1
和ax2
被定义:
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 根本不同,我该如何解决这个问题?我唯一的要求仍然是我可以在地块上的任何地方导航,而地块正在更新。
解决方案
推荐阅读
- javascript - 如何正确设置/读取 js-cookie 库中的 cookie?
- jquery - Laravel - 如何解决 GET http://localhost:8888/get/findScore?id=2 500(内部服务器错误)
- python - Flask RequestParser - 接受 dict 并读取 key+value
- r - 将具有多个输出的函数应用于按 tidyverse 中的因子拆分的数据帧
- php - 在 Laravel 搜索中显示来自多个不同表的数据
- python - 在 flask-restx / flask-restplus 的字段中允许空值
- visual-studio - “IIdentity”不包含“Score”的定义
- javascript - HTML 中的按钮 onclick 功能不断将表单输入字段重置为默认值。我怎样才能避免这种情况?
- python - 使用 AgglomerativeClustering 算法训练模型时出现内存错误
- azure-functions - Azure 函数有时会在出队时启动多个实例