首页 > 解决方案 > 将 pandas groupby 直方图绘制为子图

问题描述

我有两个要绘制的数据框。我可以使用以下内容:

def make_plots():
    fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12,5))
    with open(filen, 'rt') as f:
        dfn = pd.read_csv(f, delimiter='\t')
        dfn.plot(x='pos', ax=axes[0])
    with open(filem, 'rt') as f:
        dfm = pd.read_csv(f, delimiter='\t')
        dfm.plot(x='pos', ax=axes[1])
    fig.savefig('outfig.png')

但是,如果我的第二个图是带有组的直方图,则此代码将失败。就像是:

def make_plots():
    fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12,5))
    with open(filen, 'rt') as f:
        dfn = pd.read_csv(f, delimiter='\t')
        dfn.plot(x='pos', ax=axes[0])
    with open(filem, 'rt') as f:
        dfm = pd.read_csv(f, delimiter='\t')
        dfm.hist(by='groupname', ax=axes[1])
    fig.savefig('outfig.png')

我希望得到的是一个 12x5 的图形,其中左侧 6x5 部分用于第一个图,右侧 6x5 部分包含两个直方图,每个直方图占用大约 3x5。

标签: pythonpandasdataframeplot

解决方案


推荐阅读