如何对数据帧字典进行子绘图

2024-09-22 10:29:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从字典中分包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)

因此,我想为字典中的每个数据帧对每个列的持续时间(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()

Tags: 数据代码infor字典figrangeplt
2条回答

尝试展平轴阵列并使用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()
  • 使用.ravel来展平axes array是相当常见的。
  • math.ceil将确保有足够的行,当要打印的项目数不能被列数平均整除时
  • for-loop遍历枚举的dict keys,使用idx索引ax_array中的正确值,并使用key绘制每个数据帧
  • ^{}用于绘制数据帧
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()

enter image description here

相关问题 更多 >