【问题标题】:Matplotlib: Plot multiple lines per time series subplotMatplotlib:每个时间序列子图绘制多条线
【发布时间】:2017-05-09 15:11:30
【问题描述】:

使用子图,有没有一种 Pythonic 方法可以为每个子图绘制多条线?我有一个带有两个行索引、日期字符串和水果的 pandas 数据框,其中包含列的存储和值的数量。我想要 5 个子图,每个商店一个,日期字符串作为 x 轴,数量作为 y 轴,每个水果作为自己的彩色线。

df.plot(subplots=True)

我认为,几乎可以让我到达那里,使用适量的子图,除了它完全聚合数量而不是按水果绘制。

【问题讨论】:

    标签: python pandas matplotlib plot plotly


    【解决方案1】:

    设置
    始终提供重现您的问题的示例数据。
    我在这里提供了一些

    cols = pd.Index(['TJ', 'WH', 'SAFE', 'Walmart', 'Generic'], name='Store')
    dates = ['2015-10-23', '2015-10-24']
    fruit = ['carrots', 'pears', 'mangos', 'banannas',
             'melons', 'strawberries', 'blueberries', 'blackberries']
    rows = pd.MultiIndex.from_product([dates, fruit], names=['datestring', 'fruit'])
    df = pd.DataFrame(np.random.randint(50, size=(16, 5)), rows, cols)
    df
    

    首先,您想用pd.to_datetime 转换第一级行索引

    df.index.set_levels(pd.to_datetime(df.index.levels[0]), 0, inplace=True)
    

    现在我们可以看到我们可以直观地绘图了

    # fill_value is unnecessary with the sample data, but should be there 
    df.TJ.unstack(fill_value=0).plot()
    

    我们可以绘制所有这些

    fig, axes = plt.subplots(5, 1, figsize=(12, 8))
    
    for i, (j, col) in enumerate(df.iteritems()):
        ax = axes[i]
        col = col.rename_axis([None, None])
        col.unstack(fill_value=0).plot(ax=ax, title=j, legend=False)
    
        if i == 0:
            ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left', ncol=1)
    
    fig.tight_layout()
    

    【讨论】:

    • @piRSqaured 谢谢。很有帮助的答案;我现在对 matplotlib 的工作原理有了更好的了解。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-02
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 2014-07-27
    相关资源
    最近更新 更多