pandas 在网格中绘制多个直方图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29530355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:10:15  来源:igfitidea点击:

plotting multiple histograms in grid

pythonnumpypandasmatplotlib

提问by Alph

I am running following code to draw histograms in 3 by 3 grid for 9 varaibles.However, it plots only one variable.

我正在运行以下代码以在 3 x 3 网格中为 9 个变量绘制直方图。但是,它只绘制了一个变量。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

def draw_histograms(df, variables, n_rows, n_cols):
    fig=plt.figure()
    for i, var_name in enumerate(variables):
        ax=fig.add_subplot(n_rows,n_cols,i+1)
        df[var_name].hist(bins=10,ax=ax)
        plt.title(var_name+"Distribution")
        plt.show()

回答by RickardSjogren

You're adding subplots correctly but you call plt.showfor each added subplot which causes what has been drawn so far to be shown, i.e. one plot. If you're for instance plotting inline in IPython you will only see the last plot drawn.

您正确添加了子图,但您调用plt.show了每个添加的子图,这会导致显示到目前为止已绘制的内容,即一个图。例如,如果您在 IPython 中内联绘图,您将只会看到绘制的最后一张图。

Matplotlib provides some nice examplesof how to use subplots.

Matplotlib 提供了一些关于如何使用子图的很好的例子

Your problem is fixed like:

您的问题已修复如下:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

def draw_histograms(df, variables, n_rows, n_cols):
    fig=plt.figure()
    for i, var_name in enumerate(variables):
        ax=fig.add_subplot(n_rows,n_cols,i+1)
        df[var_name].hist(bins=10,ax=ax)
        ax.set_title(var_name+" Distribution")
    fig.tight_layout()  # Improves appearance a bit.
    plt.show()

test = pd.DataFrame(np.random.randn(30, 9), columns=map(str, range(9)))
draw_histograms(test, test.columns, 3, 3)

Which gives a plot like:

这给出了一个情节:

subplot histograms

子图直方图

回答by Zero

In case you don't really worry about titles, here's a one-liner

如果你真的不担心标题,这里有一个单行

df = pd.DataFrame(np.random.randint(10, size=(100, 9)))
df.hist(color='k', alpha=0.5, bins=10)

enter image description here

在此处输入图片说明