如何在一个图中绘制两个单独的DataFrame的列(代表每个列的子图)

时间:2018-12-12 18:55:45

标签: python matplotlib plot seaborn subplot

我有两个如下所示的DataFrame。它们在列名和结构方面完全相同。区别在于,一个数据帧是预测数据,一个是观测数据。我需要绘制一个带有子图的图,其中每个子图标题是列名,X轴是索引值,Y轴是表中的值。我需要在每个图中绘制两条线,一条来自预测的数据帧,一条来自观察到的线。以下是我一直在尝试执行的操作,但操作失败。

      08FB006     08FC001    08FC005        08GD004     08GD005
----------------------------------------------------------------
0   1.005910075 0.988765247 0.00500000  0.984376392 5.099999889
1   1.052696367 1.075232414 0.00535313  1.076066586 5.292135227
2   1.101749034 1.169026145 0.005731682 1.176162168 5.491832766
3   1.153183046 1.270744221 0.006137526 1.285419625 5.699405829
4   1.207119522 1.381030962 0.006572672 1.404662066 5.915181534
5   1.263686077 1.500580632 0.007039282 1.534784937 6.139501445
6   1.323017192 1.630141078 0.007539681 1.676762214 6.372722261
7   1.38525461  1.770517606 0.008076372 1.831653101 6.615216537
8   1.450547748 1.922577115 0.008652045 2.000609283 6.867373442
9   1.519054146 2.087252499 0.009269598 2.184882781 7.129599561
10  1.590939931 2.265547339 0.009932148 2.385834436 7.402319731

示例代码,我有81个站/列

import matplotlib.pyplot as plt
%matplotlib inline

fig, axes = plt.subplots(nrows=81, ncols=1)

newdf1.plot(ax=axes[0,0])
newdf1_pred.plot(ax=axes[0,1])

1 个答案:

答案 0 :(得分:1)

我设置了一个虚拟数据框以帮助可视化我所做的事情。

import pandas as pd
import numpy as np

obs = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
pred = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

在同一图上绘制两个数据框与绘制两列没有什么不同。您只需将它们包括在同一轴上。这是我的操作方式:

import matplotlib.pyplot as plt
%matplotlib inline

fig, axes = plt.subplots(figsize=(5,7), nrows=4, ncols=1)
for col in range(len(obs.columns)): # loop over the number of columns to plot
    obs.iloc[col].plot(ax=axes[col], label='observed') # plot observed data
    pred.iloc[col].plot(ax=axes[col], label='predicted') # plot predicted data
    axes[col].legend(loc='upper right') # legends to know which is which
    axes[col].set_title(obs.columns[col]) # titles to know which column/variable
plt.tight_layout() # just to make it easier to read the plots

这是我的输出:

enter image description here

我希望这会有所帮助。

相关问题