首页 > 解决方案 > Trouble getting a Bar Chart to Plot in Python

问题描述

This is sort of a 2 part question. I have a set of data indexed by date time index:

     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 

I'm trying to create two plots on the same figure - 1 line chart showing the closedPL and one of the MaxDrawPerPeriod represented by a bar graph. X axis would be the date time index. I'd like the bar chart to run along bottom of the graph but with limited height so as not to really interfere with the line chart. So part 1 would be how to add to that the chart and part 2 is below:

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

For some reason - I can't get the bar chart to run correctly, even when I run it on it's own. This is what it looks like and it takes 10 min just to produce this. Am i doing something wrong wtih my code? enter image description here

标签: pythondataframematplotlibplotgraph

解决方案


您正在创建与数据框中的行一样多的条,这似乎很多。每个都有自己的标签,因此总的来说它变得不可读。对于您正在寻找的那种情节,您需要使用 matplotlib。如果还没有,您将需要将索引转换为日期时间并绘制一个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()

推荐阅读