【问题标题】:How to subplot a dictionary of dataframes如何对数据框字典进行子图绘制
【发布时间】:2021-03-04 03:36:53
【问题描述】:

我想从字典中绘制 16 个数据帧,但我尝试使用 for 循环,但我不知道如何使用我的 DictDataFrame 完成我的代码:

DataFrameDict.keys() :
dict_keys([1, 10, 20, 30, 40, 47, 100, 15, 25, 35, 45, 50, 5, 105, 55, 0])
DataFrameDict[0]:

date_time   id  value   Duration_datetime   Duration(Min)

所以我想从字典中为每个数据帧的每个列 Duration(Min) 子图,但我不知道如何处理:DataFrameDict[key]['Duration(Min)']

fig = plt.figure()
fig, ax = plt.subplots(nrows=4, ncols=4)

for i in range(4):
    for j in range(4):
        subplot = ax[i, j]


plt.show()

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    尝试展平坐标轴数组并使用 zip 循环:

    fig = plt.figure()
    fig, axes = plt.subplots(nrows=4, ncols=4)
    
    for (key, data), ax in zip(DataFrameDict.items(), axes.ravel()):
        data['Duration (Min)'].plot(ax=ax)
    
        ax.set_title(f'Data for {key}')
    
    plt.show()
    

    【讨论】:

    • 我有这个错误:ValueError: too many values to unpack (expected 2)
    • @ThonyNadhir 抱歉,应该是 .items()。已更新。
    【解决方案2】:
    • 使用.ravel 来展平axes array 是相当普遍的。
    • 当要绘制的项目数不能被列数整除时,math.ceil 将确保有足够的行。
    • for-loop 遍历枚举的dict keys,使用idx 索引ax_array 中的正确值,并使用key 绘制每个数据帧。
    • pandas.DataFrame.plot 用于绘制数据框。
    import pandas as pd
    import numpy as np  # for test data
    import math
    
    # test data
    rows = 10
    keys = sorted([1, 10, 20, 30, 40, 47, 100, 15, 25, 35, 45, 50, 5, 105, 55, 0])
    df_dict = {key: pd.DataFrame({'a': np.random.randint(0, 10, size=(rows)), 'b': np.random.randint(15, 25, size=(rows)), 'Duration(Min)': np.random.randint(30, 40, size=(rows))}) for key in keys}
    
    # determine number of rows, given the number of columns
    cols = 4
    rows = math.ceil(len(keys) / cols)
    
    # create the figure with multiple axes
    fig, axes = plt.subplots(nrows=rows, ncols=cols, figsize=(16, 16))
    
    # convert the axes from a 4x4 array to a 16x1 array
    ax_array = axes.ravel()
    
    # iterate through the dataframe dictionary keys and use enumerate
    for idx, key in enumerate(keys):
        df_dict[key]['Duration(Min)'].plot(ax=ax_array[idx], ylabel='Value', title=f'DataFrame: {key}')
    plt.tight_layout()
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2020-10-22
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      • 2021-07-01
      • 2019-12-24
      • 2021-01-15
      • 1970-01-01
      • 2023-02-21
      相关资源
      最近更新 更多