在一个图上绘制来自不同文件夹的两个数据集

时间:2016-12-08 19:39:13

标签: python loops matplotlib plot

我有两个文件夹数相似的文件夹:maindirNomaindirWith。我试图在一个图上绘制文件夹中的每对类似文件:

for i in [maindirNo, maindirWith]:
for root, dirs, files in os.walk(i):
    for fil in files:
        if 'output.rsv' in fil:
            df = pd.read_csv(os.path.join(i, fil), skiprows = 9, delimiter = r'\s+', header = None)
            df['SIMULATEDm'] = mergedlevels
            df['OBSERVEDm'] = df_observed['OBSERVEDm']
            df['date'] = pd.date_range('1/1991','12/2040', freq='MS')
            if i == maindirNo:
                plt.plot(df['date'], df['SIMULATEDm'], 'b', label='No outlet')
            if i == maindirWith:
                plt.plot(df['date'], df['SIMULATEDm'], 'r', label='With outlet')
            plt.legend(loc = 'lower right')
            plt.savefig('C:/Users/sgulbin/Desktop/AGU_Conf/plots/%s.jpg' %fil)
            plt.close()

问题在于我要么在一个图上绘制所有日期集,要么为每个文件绘制一个图(我在一个图上需要两个数据集)。我假设我可以将输出附加到空数据帧然后绘制它,但有没有最简单的方法通过循环绘制它们?

P.S。我知道这有类似的问题,但不完全正确。

1 个答案:

答案 0 :(得分:0)

pandas使用matplotlib,当您创建多个绘图时,会figax。即。一列中有5个图

 fig, ax = plt.subplots(5, 1)

然后您可以使用ax[0]a[1]为绘制线选择绘图。

import matplotlib.pyplot as plt
import pandas as pd
import random

SIZE = 5

# create grid 5x1
fig, ax = plt.subplots(SIZE, 1)

# --- first folder --- blue ---

for idx in range(SIZE):

    # dataframe with random data as example
    df = pd.DataFrame([ random.randint(0,10) for _ in range(10) ])

    # draw it
    ax[idx].plot(df, 'b')

# --- second folder --- red ---

for idx in range(SIZE):

    # dataframe with random data as example
    df = pd.DataFrame([ random.randint(0,10) for _ in range(10) ])

    # draw it
    ax[idx].plot(df, 'r')

plt.show()

enter image description here