Reputation: 526
I would like to subplot 16 dataframes from a dictionary, but I tried with for loop but I don't how to finish my code with my 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)
So I would like to subplot each column Duration(Min) for each dataframe from dictionary but I don't know how to deals with : 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()
Upvotes: 1
Views: 400
Reputation: 62393
.ravel
to flatten the axes array
is fairly common.
math.ceil
will ensure there are enough rows, when the number of items to plot is not evenly divisible by the number of columns.for-loop
iterates through the enumerated dict keys
, using idx
to index the correct value from ax_array
, and using the key
to plot each dataframe.pandas.DataFrame.plot
is used to plot the dataframe.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()
Upvotes: 1
Reputation: 150735
Try flatten the axes array and loop with 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()
Upvotes: 2