【问题标题】:create a subplot of multiple histograms with titles创建带有标题的多个直方图的子图
【发布时间】:2021-10-27 03:10:11
【问题描述】:

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

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

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

【问题讨论】:

    标签: python pandas histogram subplot


    【解决方案1】:

    你必须这样循环:

    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)
    

    【讨论】:

    • 如何更改代码以使用 sns.distplot()? for ax, (name, subdf) in zip(axes.flatten(), data_new.groupby('City')): sns.distplot(data_new['CarTripDuration']) ax.set_title(name)
    • distplot 已弃用,请改用 displot 但您不能这样做,因为该函数不接受 ax 参数。你必须使用histplot。
    • 它对我有用。我想你没有专栏CarTripDuration
    猜你喜欢
    • 2016-08-04
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    • 1970-01-01
    • 2013-05-02
    • 2017-07-27
    相关资源
    最近更新 更多