【问题标题】:Is there a way to use a for-loop to quickly create sublots in matplotlib and pandas?有没有办法使用 for 循环在 matplotlib 和 pandas 中快速创建子图?
【发布时间】:2021-09-09 06:59:43
【问题描述】:

我在 Pandas 数据框中保存了几只股票的每日股价。我正在使用 python 和 Jupyter notebook。

保存后,我使用 matplotlib 绘制价格图表以检查数据。

这个想法是在一个 3 x 3 的子图中一次绘制 9 只股票。

当我想检查其他股票代码时,我必须手动更改每个子图中的每个代码,这需要很长时间并且似乎效率低下。

¿有没有办法通过某种列表和 for 循环来做到这一点?

这是我当前的代码。它有效,但似乎很长而且很难更新。 (股票代码只是先锋模型组合中的示例)。

x = price_df.index
a = price_df["P_VOO"]
b = price_df["P_VGK"]
c = price_df["P_VPL"]
d = price_df["P_IEMG"]
e = price_df["P_MCHI"]
f = price_df["P_VNQ"]
g = price_df["P_GDX"]
h = price_df["P_BND"]
i = price_df["P_BNDX"]



# Plot a figure with various axes scales
fig = plt.figure(figsize=(15,10))

# Subplot 1
plt.subplot(331)
plt.plot(x, a)
plt.title("VOO")
plt.ylim([0,550])
plt.grid(True)

plt.subplot(332)
plt.plot(x, b)
plt.title("VGK")
plt.ylim([0,400])
plt.grid(True)

plt.subplot(333)
plt.plot(x, c)
plt.title('VPL')
plt.ylim([0,110])
plt.grid(True)

plt.subplot(334)
plt.plot(x, d)
plt.title('IEMG')
plt.ylim([0,250])
plt.grid(True)

plt.subplot(335)
plt.plot(x, e)
plt.title('MCHI')
plt.ylim([0,75])
plt.grid(True)

plt.subplot(336)
plt.plot(x, f)
plt.title('P_VNQ')
plt.ylim([0,55])
plt.grid(True)

plt.subplot(337)
plt.plot(x, g)
plt.title('P_GDX')
plt.ylim([0,8])
plt.grid(True)

plt.subplot(338)
plt.plot(x, h)
plt.title('P_BND')
plt.ylim([0,200])
plt.grid(True)

plt.subplot(339)
plt.plot(x, i)
plt.title('P_BNDX')
plt.ylim([0,350])
plt.grid(True)

plt.tight_layout()

【问题讨论】:

    标签: python pandas for-loop matplotlib plot


    【解决方案1】:

    尝试使用DataFrame.plot 并启用subplots,设置layoutfigsize

    axes = df.plot(subplots=True, title=df.columns.tolist(),
                   grid=True, layout=(3, 3), figsize=(15, 10))
    
    plt.tight_layout()
    plt.show()
    

    或使用plt.subplots 设置布局,然后使用DataFrame.plot 在这些轴上绘图:

    # setup subplots
    fig, axes = plt.subplots(nrows=3, ncols=3, figsize=(15, 10))
    # Plot DataFrame on axes
    df.plot(subplots=True, ax=axes, title=df.columns.tolist(), grid=True)
    
    plt.tight_layout()
    plt.show()
    


    示例数据和导入:

    import numpy as np
    import pandas as pd
    from matplotlib import pyplot as plt
    
    np.random.seed(5)
    df = pd.DataFrame(np.random.randint(10, 100, (10, 9)),
                      columns=list("ABCDEFGHI"))
    

    df:

        A   B   C   D   E   F   G   H   I
    0  88  71  26  83  18  72  37  40  90
    1  17  86  25  63  90  37  54  87  85
    2  75  57  40  94  96  28  19  51  72
    3  11  92  26  88  15  68  10  90  14
    4  46  61  37  41  12  78  48  93  29
    5  28  17  40  72  21  77  75  65  13
    6  88  37  39  43  99  95  17  26  24
    7  41  19  48  57  26  15  44  55  69
    8  34  23  41  42  86  54  15  24  57
    9  92  10  17  96  26  74  18  54  47
    

    【讨论】:

    • 这也有效。谢谢你。由于某种原因,答案消失了几天。
    【解决方案2】:

    这个实现在你的情况下不可行吗?

    x = price_df.index
    cols = ["P_VOO","P_VGK",...] #Populate before running
    ylims = [[0,550],...] #Populate before running
    
    # Plot a figure with various axes scales
    fig = plt.figure(figsize=(15,10))
    
    # Subplot 1
    for i, (col, ylim) in enumerate(zip(cols, ylims)):
        plt.subplot(331+i)
        plt.plot(x, price_df[col])
        plt.title(col.split('_')[1])
        plt.ylim(ylim)
        plt.grid(True)
    

    没有在我的本地运行代码,可能有一些小错误。但是你明白了,对吧?

    【讨论】:

    • 另外,列表中的enumerate 返回索引和值。
    • 另一方面,zip 用于同时需要两个或多个列表的元素。例如。 zip([1,2,3], [2,3,4]) 返回 (1,2)(2,3)(3,4)
    猜你喜欢
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-30
    相关资源
    最近更新 更多