【问题标题】:matplotlib loop make subplot for each categorymatplotlib 循环为每个类别制作子图
【发布时间】:2017-10-12 15:15:07
【问题描述】:

我正在尝试编写一个循环,该循环将生成一个包含 25 个子图的图形,每个国家/地区各 1 个。我的代码制作了一个包含 25 个子图的图形,但这些图是空的。我可以进行哪些更改以使数据显示在图表中?

fig = plt.figure()

for c,num in zip(countries, xrange(1,26)):
    df0=df[df['Country']==c]
    ax = fig.add_subplot(5,5,num)
    ax.plot(x=df0['Date'], y=df0[['y1','y2','y3','y4']], title=c)

fig.show()

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    您对 matplotlib 绘图函数和 pandas 绘图包装器感到困惑。
    您遇到的问题是 ax.plot 没有任何 xy 参数。

    使用ax.plot

    在这种情况下,将其命名为 ax.plot(df0['Date'], df0[['y1','y2']]),不带 xytitle。可能单独设置标题。 示例:

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    
    countries = np.random.choice(list("ABCDE"),size=25)
    df = pd.DataFrame({"Date" : range(200),
                        'Country' : np.repeat(countries,8),
                        'y1' : np.random.rand(200),
                        'y2' : np.random.rand(200)})
    
    fig = plt.figure()
    
    for c,num in zip(countries, xrange(1,26)):
        df0=df[df['Country']==c]
        ax = fig.add_subplot(5,5,num)
        ax.plot(df0['Date'], df0[['y1','y2']])
        ax.set_title(c)
    
    plt.tight_layout()
    plt.show()
    

    使用 pandas 绘图包装器

    在这种情况下,通过df0.plot(x="Date",y =['y1','y2']) 绘制您的数据。

    例子:

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    
    countries = np.random.choice(list("ABCDE"),size=25)
    df = pd.DataFrame({"Date" : range(200),
                        'Country' : np.repeat(countries,8),
                        'y1' : np.random.rand(200),
                        'y2' : np.random.rand(200)})
    
    fig = plt.figure()
    
    for c,num in zip(countries, xrange(1,26)):
        df0=df[df['Country']==c]
        ax = fig.add_subplot(5,5,num)
        df0.plot(x="Date",y =['y1','y2'], title=c, ax=ax, legend=False)
    
    plt.tight_layout()
    plt.show()
    

    【讨论】:

    • 如何在整个图的底部添加一个图例?
    • 要添加图例,我想将您推荐给this answer,因为这可能超出了此问题的范围。
    • 对于使用 Python 3 的用户,您需要将 xrange 更改为 range
    【解决方案2】:

    我不太记得如何使用原始子情节系统,但您似乎正在重写情节。无论如何,您应该看看gridspec。检查以下示例:

    import matplotlib.pyplot as plt
    import matplotlib.gridspec as gridspec
    
    fig = plt.figure()
    
    gs1 = gridspec.GridSpec(5, 5)
    countries = ["Country " + str(i) for i in range(1, 26)]
    axs = []
    for c, num in zip(countries, range(1,26)):
        axs.append(fig.add_subplot(gs1[num - 1]))
        axs[-1].plot([1, 2, 3], [1, 2, 3])
    
    plt.show()
    

    结果如下:

    只需将示例替换为您的数据,它应该可以正常工作。

    注意:我注意到您使用的是xrange。我使用了range,因为我的 Python 版本是 3.x。适应你的版本。

    【讨论】:

    • 使用for num, c in enumerate(countries, 1):会更加pythonic/惯用+未来/向后兼容
    猜你喜欢
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    • 2012-11-15
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    相关资源
    最近更新 更多