python - Matplotlib subplot2grid 在 pandas 0.16.1 中绘制 IndexError

标签 python pandas matplotlib histogram

我有 (5) 个 pandas 系列,我正在尝试在 (5) 个图表上绘制。我想让它们看起来像这样的格式,第五个图表位于最后一行,居中(不要关注图表的内容,只关注定位) enter image description here

但是在 pandas 0.16.1 中,我在第 5 个图表上收到索引错误。这是我的问题的 MCVE 示例,你们可以复制并粘贴并亲自尝试。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')

fig = plt.figure() 

firstperiod = pd.Series({1:1, 2:2, 3:3, 4:3, 5:4}) 
secondperiod = pd.Series({1:1, 2:1, 3:2, 4:2}) 
thirdperiod = pd.Series({1:4, 2:4, 3:5, 4:1, 5:1, 6:3}) 
fourthperiod = pd.Series({1:3, 2:3, 3:1, 4:6, 5:7, 6:5})
fifthperiod = pd.Series({1:2, 2:2, 3:1, 4:5, 5:5})

ax1 = plt.subplot2grid((6,4), [0,0], 2, 2) 
firstperiod.plot(kind='hist', bins=5) 

ax2 = plt.subplot2grid((6,4), [0,2], 2, 2) 
secondperiod.plot(kind='hist', bins=4) 

ax3 = plt.subplot2grid((6,4), [2,1], 2, 2) 
thirdperiod.plot(kind="hist", bins=6) 

ax4 = plt.subplot2grid((6,4), [2,2], 2, 2) 
fourthperiod.plot(kind="hist", bins=6) 

ax5 = plt.subplot2grid((6,4), [4,1], 2, 2) 
fifthperiod.plot(kind="hist", bins=5) 

plt.tight_layout() 
plt.show()

它执行到最后一个(第 5 个)图表,然后弹出:

索引错误:索引 4 超出尺寸为 4 的轴 0 的范围

什么给了?以及如何解决这个问题?

提前感谢大家,非常感谢。

最佳答案

这就是您想要的...我添加了 plt.ion() 使其进入交互模式,并添加了 plt.draw() 来添加每个图形正如您所定义的。

通过这样做,很明显轴被定义为 (y,x) 而不是 (x,y)...

This reference将来也可能有所帮助

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')

plt.ion()
fig = plt.figure()

firstperiod = pd.Series({1:1, 2:2, 3:3, 4:3, 5:4}) 
secondperiod = pd.Series({1:1, 2:1, 3:2, 4:2}) 
thirdperiod = pd.Series({1:4, 2:4, 3:5, 4:1, 5:1, 6:3}) 
fourthperiod = pd.Series({1:3, 2:3, 3:1, 4:6, 5:7, 6:5})
fifthperiod = pd.Series({1:2, 2:2, 3:1, 4:5, 5:5})

ax1 = plt.subplot2grid((3,4), (0,0), colspan=2) 
firstperiod.plot(kind='hist', bins=5) 
plt.draw()
raw_input()

ax2 = plt.subplot2grid((3,4), (0,2), colspan=2) 
secondperiod.plot(kind='hist', bins=4) 
plt.draw()
raw_input()

ax3 = plt.subplot2grid((3,4), (1,0), colspan=2) 
thirdperiod.plot(kind="hist", bins=6) 
plt.draw()
raw_input()

ax4 = plt.subplot2grid((3,4), (1,2), colspan=2)
fourthperiod.plot(kind="hist", bins=6) 
plt.draw()
raw_input()

ax5 = plt.subplot2grid((3,4), (2,1), colspan=2)
fifthperiod.plot(kind="hist", bins=5)
plt.draw()
raw_input()

plt.tight_layout()
plt.draw()

我将列高从 6 更改为 3,因为上面显示的图表的 colspanrowspan 的两倍

关于python - Matplotlib subplot2grid 在 pandas 0.16.1 中绘制 IndexError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30657804/

相关文章:

python - 将字符串匹配到元组列表

python - 为什么 pandas 格式化我的日期时间 1999-12-02 19 :30:00+00:00

python & pandas - 如何计算 DataFrame 中列条件下的频率?

python - Matplotlib 中的极地等高线图

python - 在 python 中导入 Pandas 会改变 matplotlib 处理日期时间对象的方式吗?

Python-如何检查程序在运行时是否被用户中止?

python - 根据文本将值从一个数据帧平均分配到另一个数据帧

python - PIL - 对每个像素应用相同的操作

python - 具有已定义名称范围的 Pandas 数据框到 Excel

python - 尝试从 csv 绘制数据集而不是生成数据集时,与 scikit-learn fit() 方法不匹配