【问题标题】:Populate subplots with histograms within for loop在 for 循环中使用直方图填充子图
【发布时间】:2021-11-07 09:06:20
【问题描述】:

我在一个文件夹中有一组 7 个 *xls 文件(直到现在),这些是每个月的统计数据,我用 Pandas 阅读了所有这些文件,然后我选择了名为“Gap”的列并进行了一些过滤以保留在职的。我试图在一个子图中绘制每个“间隙”的直方图(子图中每月的间隙)。 我做的代码是:

pato = r'D:\Inves\Pdoc\Cata_2021'
#os.chdir(pato)

file_list = glob.glob(pato + r"\*.xls")
print('file_list {}'.format(file_list))
print(file_list)



fig, axs = plt.subplots(4,3, figsize=(15, 6), sharex=True, sharey=True)

a = 4 
b = 3
# this for loop read all files with Pandas and 
for proce in file_list:
    df_cat = pd.read_excel(proce)
    #print(df_cat.head())
    df_cat_sha = df_cat[(df_cat.Prof.between(0, 75))]
    print(df_cat_sha)
    m = 0
   # Here I tried to create the subplot's and populate them
    for i in range(a):
        for j in range(b):
            df_cat_sha.Gap.hist(bins=18, ax=axs[i, j], 
                            color='green', alpha=0.75)
            m +=1
plt.show()

我得到了以下情节(在Plotting two histograms from a pandas DataFrame in one subplot using matplotlib 的帮助下)

但是,您可以看到在每个子图中都有多个直方图,这是我不想要的。

想要的输出就像这个例子

您有什么提示可以在一个子图中仅从我的 DataFrame 中绘制一个直方图“Gap”吗?这里我也附上 xls 格式的文件 (https://drive.google.com/drive/folders/1MbuTMQpuc79nRYFGL-UAdmvo9r2AzhxA?usp=sharing)

提前致谢

托尼诺

【问题讨论】:

    标签: python pandas dataframe subplot


    【解决方案1】:

    由于您指定了bins=18,每个数据框根据其Gap 列的minmax 分为18 个子范围。当 minmax 在两个数据帧之间不匹配时,您会得到未对齐的 bin。

    您可以根据所有数据帧中Gap 列的全局minmax 显式定义这18 个bin 的边缘,而不是指定bins=18

    from pathlib import Path
    
    pato = Path(r'D:\Inves\Pdoc\Cata_2021')
    df_list = [pd.read_csv(file) for file in pato.glob('*.xls')]
    
    tmp = pd.concat(df_list)
    gap = tmp.loc[tmp['Prof'].between(0, 75), 'Gap']
    bins = np.linspace(gap.min(), gap.max(), 18) # the bin edges
    
    a, b = 4, 3
    fig, axs = plt.subplots(a, b, figsize=(15, 6), sharex=True, sharey=True)
    
    for df in df_list:
        for i in range(a):
            for j in range(b):
                cond = df['Prof'].between(0, 75)
                df.loc[cond, 'Gap'].hist(bins=bins, ax=axs[i,j], color='green', alpha=0.75)
    

    【讨论】:

    • 感谢您提供有关 bin 的知识,太好了,但是,我不清楚问我的疑问,将更改为 plot 像:ax[0,0,0] 01 的间隙直方图。 xls 和来自 02.xls 的 ax[0,1,0] 数据,在 ax[0,0,1] 03.xls 等等,有点像matplotlib.org/stable/gallery/scales/log_demo.html
    • 我不确定我是否理解您的要求。可以稍微澄清一下吗?
    • 不同,抱歉不清楚,我试图在一个图中有 12 个子图,每月一个子图,我有 12 个 *xls 文件(每月一个),我试图绘制GAP 数据帧直方图,例如在 ax[0,0,0].hist(df.loc[cond, 'Gap']...) 将代表第一个文件,然后第二个文件将绘制在 ax[0, 1,0].hist(df.loc[cond, 'Gap']...),第三个文件将绘制在 ax[0,0,1].hist(df.loc[cond, 'Gap'] ...),第四个文件将在 ax[1,0,0].hist(df.loc[cond, 'Gap']...),提前谢谢你
    • 我添加了我想要在主要问题@Code Different 中获得的所需输出
    • 每个图表有2个系列,有12个图表。 12个文件怎么能出24个系列?
    猜你喜欢
    • 2020-04-02
    • 2021-06-27
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多