首页 > 解决方案 > 如何在同一张图表中同时绘制价格和交易量

问题描述

我有一个如下所述的数据框:

Date,Time,Price,Volume
31/01/2019,09:15:00,10691.50,600
31/01/2019,09:15:01,10709.90,13950
31/01/2019,09:15:02,10701.95,9600
31/01/2019,09:15:03,10704.10,3450
31/01/2019,09:15:04,10700.05,2625
31/01/2019,09:15:05,10700.05,2400
31/01/2019,09:15:06,10698.10,3000
31/01/2019,09:15:07,10699.90,5925
31/01/2019,09:15:08,10699.25,5775
31/01/2019,09:15:09,10700.45,5925
31/01/2019,09:15:10,10700.00,4650
31/01/2019,09:15:11,10699.40,8025
31/01/2019,09:15:12,10698.95,5025
31/01/2019,09:15:13,10698.45,1950
31/01/2019,09:15:14,10696.15,3900
31/01/2019,09:15:15,10697.15,2475
31/01/2019,09:15:16,10697.05,4275
31/01/2019,09:15:17,10696.25,3225
31/01/2019,09:15:18,10696.25,3300

数据框包含大约 8000 行。我想在同一张图表中同时绘制价格和交易量。(音量范围:0 - 8,00,000)

标签: pythonpython-3.xmatplotlib

解决方案


假设您想比较价格和数量与时间,试试这个:

df = pd.read_csv('your_path_here')
df.plot('Time', ['Price', 'Volume'], secondary_y='Price')

在此处输入图像描述

编辑:x轴定制

由于您想要自定义 x 轴,请尝试以下操作(这只是您可以遵循的基本示例):

# Create a Datetime column while parsing the csv file
df = pd.read_csv('your_path_here', parse_dates= {'Datetime': ['Date', 'Time']})

然后您需要创建两个列表,一个包含 x 轴上的位置,另一个包含标签。假设您希望每 5 秒贴一次标签(您可以在 30 分钟提出请求,但不能使用您提供的数据)

positions = [p for p in df.Datetime if p.second in range(0, 60, 5)]
labels = [l.strftime('%H:%M:%S') for l in positions]

然后你绘制将位置和标签列表传递给set_xticksset_xticklabels

ax = df.plot('Datetime', ['Price', 'Volume'], secondary_y='Price')
ax.set_xticks(positions)
ax.set_xticklabels(labels)

推荐阅读