将imshow色彩映射与Python Pandas子图线图组合在一起

时间:2014-04-15 06:13:34

标签: python matplotlib pandas time-series colormap

我有Pandas DataFrame有一对列 - 每对都有一个测量列,我想要绘制为折线图,另一列我要绘制为一个imshow色彩映射表示严重性指标。

一个简单的例子:

from random import *
import pandas as pd

randBinList = lambda n: [randint(0,1) for b in range(1,n+1)]
rng = pd.date_range('1/1/2011', periods=72, freq='H')
tslist = {}
for measurement_num in range(3):
    measurement_name = 'Measurement'+str(measurement_num)
    tslist[measurement_name] = pd.DataFrame({'Value': randn(len(rng)),'Severity': randn(len(rng))})

ts = pd.concat(tslist, axis=1)
ts.head()

一个简单的DataFrame结果:

enter image description here

我尝试制作我的预期剧情的依据是:Shade the background of matplotlib based on array and colormapColormap entire subplot

PointList = ts.columns.levels[0].tolist()
y = ts[PointList[0]]['Value'].values
x = np.arange(len(y))
t = ts[PointList[0]]['Severity'].values

fig, ax = plt.subplots(len(PointList), 1, figsize=(18,10))    
ax[0].plot(x, y, c='black')

ymin, ymax = ax[0].get_ybound()
xmin, xmax = ax[0].get_xbound()

im = ax[1].imshow(t.reshape(1, t.size), extent=[xmin,x.max(),ymin,ymax], alpha=.5, cmap=plt.cm.RdYlGn)
ax[0].set_title(PointList[0])


plotcounter = 1
for point in PointList[1:]:

    y = ts[point]['Value'].truncate(before=cutoffdate).values
    x = np.arange(len(y))
    t = ts[point]['Severity'].truncate(before=cutoffdate).values

    ax[plotcounter].plot(x, y, c='black', )

    ymin, ymax = ax[plotcounter].get_ybound()
    xmin, xmax = ax[plotcounter].get_xbound()

    im = ax[plotcounter].imshow(t.reshape(1, t.size), extent=[xmin,x.max(),ymin,ymax], alpha=.5, cmap=plt.cm.RdYlGn)
    ax[plotcounter].set_aspect(ax[0].get_aspect())
    ax[plotcounter].set_title(point)


    plotcounter += 1


plt.tight_layout()
plt.show()

导致:

enter image description here

我在第一个子情节中遇到imshow问题。我正在寻找一种更优雅的解决方案,可以更好地与Pandas集成并产生子图。另外,我想将pandas.tseries.index.DatetimeIndex用作x轴,而不是仅使用数字。

0 个答案:

没有答案