Plot a specific number of plots in a loop using multiple dfs from a dictionary (python, dict, multiple plots)

Viewed 53

I have a dictionary of dfs as in this example:

time = ['x1', 'x2', 'x3', 'x4', 'x5']
val = [1.1,1.2,1.3,1.4,1.5]

my_dict = {
    "df_1": pd.DataFrame(list(zip(time, val)), columns = ['time', 'df_1']),
    "df_2": pd.DataFrame(list(zip(time, [e*0.1 for e in val])), columns = ['time', 'df_2']),
    "df_3": pd.DataFrame(list(zip(time, [e*0.2 for e in val])), columns = ['time', 'df_3']),
    "df_4": pd.DataFrame(list(zip(time, [e*0.3 for e in val])), columns = ['time', 'df_4']), 
    "df_5": pd.DataFrame(list(zip(time, [e*0.4 for e in val])), columns = ['time', 'df_5'])
}

And I can plot these as in:

for k,v in my_dict.items():
    plt.plot(v['time'], v[v.columns[1]], label = v.columns[1])
    plt.legend()

enter image description here

However, the actual dict I have is much larger and I would like to have only several subplots such as this one with no more than 7 lines per plot. In other words, if I have

n_fea = len(my_dict.keys())

I want, the following number of subplots:

n_plots = int(np.round(len(my_dict.keys()) / 7))

with no more than 7 lines per plot.

Note: I want multiple lines per plot, not a subplot per df!

I am not sure what is the most optimal way about it. Thanks!

1 Answers

Here is a way

# define the number max of lines per plot
nb_lines = 7 # change to any value

# number of necessary plots
nb_plots = int(np.ceil(len(my_dict)/nb_lines))

# create all the subplots needed
fig, axes = plt.subplots(nrows=nb_plots)
# add lines to each plot until reach the maximum wanted
for i, (_key, _df) in enumerate(my_dict.items()):
    _df.plot(x='time', y=_key, label = _key, ax=axes[i//nb_lines])
plt.show()
Related