创建带有标题的多个直方图的子图

create a subplot of multiple histograms with titles

我有一个数据框,其中一个名为“CityName”的列重复城市名称,另一个名为“CarTripDuration”的列显示多个汽车旅行事件。我想为每个城市创建一个直方图,显示汽车行程持续时间。

以下代码在具有相同标题(即 CarTripDuration)的单独绘图中为每个城市生成直方图。但是,我想要单个图中的所有直方图(例如,10 行乘 5 列)并且每个图都具有直方图对应的城市标题。

ax = data.groupby(['CityName']).hist(column='CarTripDuration')

你必须像这样做一个循环:

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

N = 100
df = pd.DataFrame({'City': np.random.choice(['London', 'Paris', 'Madrid', 'Berlin'], size=N),
                   'CarTripDuration': np.random.randint(10, 100, N)})

# Create subplots 
fig, axes = plt.subplots(nrows=2, ncols=2)
fig.subplots_adjust(hspace=0.5)
fig.suptitle('Distributions of CarTripDuration by City')

# Generate histograms
for ax, (name, subdf) in zip(axes.flatten(), df.groupby('City')):
    subdf.hist('CarTripDuration', ax=ax)
    ax.set_title(name)

plt.show()

更新:

使用seaborn:

import seaborn as sns
sns.set()

subdf.hist(...)替换为:

sns.histplot(subdf, x='CarTripDuration', ax=ax)