在Python中绘制条形图时遇到问题

2024-06-07 04:58:58 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个由两部分组成的问题。我有一组按日期时间索引的数据:

     DateTime,  ClosedPL,  MaxClosedDraw,   Max,  MaxDrawPerPeriod
1/6/2012 10:52,     -7350,         -20643,     0,                 0
1/6/2012 12:00,         0,         -20643,     0,                 0
1/6/2012 14:09,         0,         -20643,     0,                 0
1/6/2012 14:29,         0,         -20643,     0,                 0
1/6/2012 14:30,         0,         -20643,     0,            -20643
1/8/2012 18:00,         0,              0,   882,                 0
1/9/2012 8:59,          0,           -924,   882,                 0
1/9/2012 9:00,          0,          -1155,   882,                 0
1/9/2012 10:00,         0,          -3423,   882,                 0
1/9/2012 11:03,         0,          -3549,   882,                 0
1/9/2012 12:10,         0,          -3549,   882,                 0
1/9/2012 13:27,         0,          -3549,   882,                 0
1/9/2012 14:17,      3250,          -3549,   882,             -3549
1/9/2012 14:26,         0,              0,  1218,                 0
1/9/2012 14:29,     -1254,          -3318,  1218,                 0
1/9/2012 14:30,         0,          -3318,  1218,                 0
1/9/2012 18:02,         0,          -3654,  1218,             -3654
1/10/2012 8:22,      1244,              0,  6426,                 0
1/10/2012 9:00,         0,          -1869,  6426,                 0
1/10/2012 9:37,         0,          -2856,  6426,                 0
1/10/2012 10:00,        0,          -3276,  6426,                 0 

我试图在同一个figure-1折线图上创建两个图,分别显示closedPL和一个由条形图表示的maxDrawperPerPeriod。X轴将是日期时间索引。我希望条形图沿着图表的底部运行,但高度有限,这样就不会真正干扰折线图。因此,第一部分将是如何添加到图表中,第二部分如下:

stats_df.plot(kind='line', y='ClosedPL_Accum')
stats_df.plot(kind='bar', y='MaxDrawPerPeriod')
plt.show()

出于某种原因-我不能让条形图正确运行,即使我自己运行它。这就是它看起来的样子,它需要10分钟才能产生这个。我的代码有问题吗? enter image description here


Tags: 数据dfdatetimeplotstats图表时间max
1条回答
网友
1楼 · 发布于 2024-06-07 04:58:58

你在数据帧中创建的条数和行数是一样多的。每一个都有自己的标签,总的来说,它变得不可读。对于要查找的绘图类型,需要使用matplotlib。如果索引还没有被转换为datetime,则需要将其转换为bar绘图。然后创建一个双轴axtwin = ax.twinx(),并将线绘制到它。反之亦然

import matlotlib.pyplot as plt

fig, ax = plt.subplots()

ax.bar(df.index, df['MaxDrawPerPeriod'])
axtwin = ax.twinx()
axtwin.plot(df.index, df['ClosedPL_Accum'])

ax.set_ylim(...)     # you need to set the limits to the numbers you need
axtwin.set_ylim(...)

plt.show()

相关问题 更多 >