Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

plotting with subplots in a loop

z = {'A': [0.3618426, 0.36146951], 'B': [1.8908799, 1.904695], 'C': [2.1813462e+08, 2.1833622e+08], 'D': [0.89925492, 0.89953589], 'E': [2.6356747, 2.6317911], 'F': [2.2250445e+08, 2.2501808e+08], 'G': [2.0806053e+08, 2.0691238e+08], 'H': [0.37242803, 0.37611806]}
k = [1,2]

for key in z:
plt.subplot(4,4,1)
plt.plot(k,[z[key][0],z[key][1]], 'ro-')
plt.show()

I will try to be clear. z is a dictionary which varies in size. What I would like to do is plot the dictionary quantities say 4 columns but the rows should increase based on how many plots are being generated, for examples if there are 16 keys to plot I should end up with a 4 row 4 column figures.How can I do this?

like image 458
Sanjay Avatar asked Apr 14 '26 00:04

Sanjay


1 Answers

The basic form of drawing multiple graphs is the following method As a prerequisite, you need to decide on just the number of columns. cols=3 The rest of the looping process is completed by the number of dictionaries.

import matplotlib.pyplot as plt
import pandas as pd
import math

z = {'A': [0.3618426, 0.36146951], 'B': [1.8908799, 1.904695], 'C': [2.1813462e+08, 2.1833622e+08], 'D': [0.89925492, 0.89953589], 'E': [2.6356747, 2.6317911], 'F': [2.2250445e+08, 2.2501808e+08], 'G': [2.0806053e+08, 2.0691238e+08], 'H': [0.37242803, 0.37611806]}
k = [1,2]

cols = 3
rows = math.ceil(len(z) / cols)

fig, axes = plt.subplots(rows, cols, figsize=(16,12))

dict_keys = [k for k in z.keys()]

l = 0
for i in range(rows):
    for j in range(cols):
        if len(z) == l:
            break
        else:
            key = dict_keys[i+j]
            axes[i][j].plot(k, [z[key][0],z[key][1]], 'ro-')
        l += 1

plt.show()

enter image description here

like image 136
r-beginners Avatar answered Apr 15 '26 12:04

r-beginners



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!