I do realize this has already been addressed here (e.g., matplotlib loop make subplot for each category, Add a subplot within a figure using a for loop and python/matplotlib). Nevertheless, I hope this question was different.
I have customized plot function pretty-print-confusion-matrix stackoverflow & github. Which generates below plot

I want to add the above-customized plot in for loop to one single plot as subplots.
for i in [somelist]:
pretty_plot_confusion_matrix(i, annot=True, cmap="Oranges", fmt='.2f', fz=11,
lw=0.5, cbar=False, figsize=[5,5], show_null_values=0, pred_val_axis='y')
# Add/append plot to subplots
Example of Desired Output:

Okay so I went through the library's github repository and the issue is that the figure and axes objects are created internally which means that you can't create multiple plots on the same figure. I created a somewhat hacky solution by forking the library. This is the forked library I created to do what you want. And here is a an example piece of code:
matrices = [np.array( [[13, 0, 1, 0, 2, 0],[ 0, 50, 2, 0, 10, 0],[ 0, 13, 16, 0, 0, 3],[ 0, 0, 0, 13, 1, 0],[ 0, 40, 0, 1, 15, 0],[ 0, 0, 0, 0, 0, 20]]),
np.array( [[13, 0, 1, 0, 2, 0],[ 0, 50, 2, 0, 10, 0],[ 0, 13, 16, 0, 0, 3],[ 0, 0, 0, 13, 1, 0],[ 0, 40, 0, 1, 15, 0],[ 0, 0, 0, 0, 0, 20]]),
np.array( [[13, 0, 1, 0, 2, 0],[ 0, 50, 2, 0, 10, 0],[ 0, 13, 16, 0, 0, 3],[ 0, 0, 0, 13, 1, 0],[ 0, 40, 0, 1, 15, 0],[ 0, 0, 0, 0, 0, 20]]),
np.array( [[13, 0, 1, 0, 2, 0],[ 0, 50, 2, 0, 10, 0],[ 0, 13, 16, 0, 0, 3],[ 0, 0, 0, 13, 1, 0],[ 0, 40, 0, 1, 15, 0],[ 0, 0, 0, 0, 0, 20]]),
np.array( [[13, 0, 1, 0, 2, 0],[ 0, 50, 2, 0, 10, 0],[ 0, 13, 16, 0, 0, 3],[ 0, 0, 0, 13, 1, 0],[ 0, 40, 0, 1, 15, 0],[ 0, 0, 0, 0, 0, 20]]),
np.array( [[13, 0, 1, 0, 2, 0],[ 0, 50, 2, 0, 10, 0],[ 0, 13, 16, 0, 0, 3],[ 0, 0, 0, 13, 1, 0],[ 0, 40, 0, 1, 15, 0],[ 0, 0, 0, 0, 0, 20]]),
np.array( [[13, 0, 1, 0, 2, 0],[ 0, 50, 2, 0, 10, 0],[ 0, 13, 16, 0, 0, 3],[ 0, 0, 0, 13, 1, 0],[ 0, 40, 0, 1, 15, 0],[ 0, 0, 0, 0, 0, 20]]),
np.array( [[13, 0, 1, 0, 2, 0],[ 0, 50, 2, 0, 10, 0],[ 0, 13, 16, 0, 0, 3],[ 0, 0, 0, 13, 1, 0],[ 0, 40, 0, 1, 15, 0],[ 0, 0, 0, 0, 0, 20]]),
np.array( [[13, 0, 1, 0, 2, 0],[ 0, 50, 2, 0, 10, 0],[ 0, 13, 16, 0, 0, 3],[ 0, 0, 0, 13, 1, 0],[ 0, 40, 0, 1, 15, 0],[ 0, 0, 0, 0, 0, 20]])]
fig = plt.figure(tight_layout=True)
ax = fig.add_gridspec(3,3)
ax_list = [] #list containing axes objects
for i in range(9):
ax_list.append(fig.add_subplot(ax[i%3,i//3]))
df_cm = DataFrame(matrices[i], index=range(1,7), columns=range(1,7))
pretty_plot_confusion_matrix(df_cm, ax_list[i], annot=True, cmap="Oranges", fmt='.2f', fz=7,
lw=0.5, cbar=False, show_null_values=0, pred_val_axis='y')
plt.show()
Let me know if there are any issues (Oh and be careful with fontsizes).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With