如何在同一个 jupyter 笔记本单元中显示多个 pandas 系列直方图?

use*_*074 5 matplotlib histogram dataframe pandas jupyter-notebook

我有一个具有明显分层的数据集,我正在寻找表明其直方图存在差异的图形证据。假设我的数据集看起来像

id | cat | hour
---------------
1  | a   | 14
5  | c   | 9
Run Code Online (Sandbox Code Playgroud)

如果我尝试绘制固定分类变量的每个直方图,那么我会得到重叠的图。例如,如果我写

unique_cats = list(df["cat"].unique())
for cat in unique_cats:
    df[df["cat"] == cat]["hour"].hist(bins=24, rwidth=0.9,
                                      normed=True, alpha=0.3)
Run Code Online (Sandbox Code Playgroud)

然后我得到一堆重叠的直方图。这是一个屏幕截图:

重叠直方图

如何让我的直方图在我的 jupyter 笔记本中拥有自己的单独行?

Imp*_*est 5

plt.figure()您可能想要为每个类别创建一个新图窗 ( ):

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

df = pd.DataFrame({"cat": np.random.choice(list("ABC"), size=100),
                  "hour" : np.random.rand(100)})
unique_cats = list(df["cat"].unique())
for cat in unique_cats:
    plt.figure()
    df[df["cat"] == cat]["hour"].hist(bins=24, rwidth=0.9,
                                      normed=True, alpha=0.3)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述