create subplots from dict in python

To create subplots from a dictionary data in python using matplotlib, you can make use of subplot function provided by the matplotlib library.

Here's the code:

main.py
import matplotlib.pyplot as plt

fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(10, 10))

data = {
    "plot1": [1, 2, 3],
    "plot2": [4, 5, 6],
    "plot3": [7, 8, 9],
    "plot4": [10, 11, 12]
}

i, j = 0, 0
for key, value in data.items():
    axs[i, j].plot(value)
    axs[i, j].set_title(key)
    j += 1
    if j == 2:
        i += 1
        j = 0

plt.show()
370 chars
22 lines

In the above code, subplots function creates 2 rows and 2 columns of subplots with figure size of 10x10. Then we create a dictionary data with values for each plot. Using items function, we loop over the dictionary. In each iteration, we pick one of the axis to plot the data using plot function, set a title using set_title function, and iterate over the remaining axis of the subplot, row-wise. Finally, we use plt.show() function to display the subplots.

gistlibby LogSnag