Problem with looping subplot array positions using variable from list

Question:

time= 11.0, 11.3, 11.4, 21.0, 22.0, 22.1, 98.0, 98.1, 98.2 

measurement= 13, 13.5, 13, 15, 16, 15, 14, 12, 14

epoch= [[11.0, 11.3, 11.4], [21.0, 22.0, 22.1], [98.0, 98.1, 98.2]] 

I try to loop and plot these in formation where is 2 plots side by side and amount of rows comes from another function.

I have tried

import matplotlib.pyplot as plt
import math

epochs = len(epoch) #how many sets of data from similar time period.
rows = math.ceil(epochs/2) #I will have two plots on each row so I divide amount epochs by 2 to get correct amount of rows 



fig1, axes1 = plt.subplots(rows, 2)

for i in range(rows):
    for j in range(2):       
        axes1[i, j].plot(time, measurement)
        for k in epoch:
            plt.xlim(min(k)+0.01, max(k)+0.01)

I am trying to achieve a code that would plot supblots in (1,2,x) formation and use different x.lim for each plot.

Let me know if I need to clarify something. This is difficult to explain for me. So I am sorry and very grateful for everyones time.

Edit:

I can use this to loop xlim and amount of plots correctly But I need to do same with array of plots so there are multiple plots per row.

import matplotlib.pyplot as plt

for i in epoch:
    plt.plot(time, measurement, '.')
    plt.xlabel('time vs detection')
    plt.ylabel('magnitude')
    plt.xlim(min(i), max(i)) 
    plt.show()

And I can use this to get the array of plots right:

fig1, axes1 = plt.subplots(rows, 2)

for i in range(rows):
    for j in range(2):       
        axes1[i, j].plot(time, measurement)

But I am unable to put those codes together.

Thank you so much for your time.

Asked By: Joonatan

||

Answers:

I think you can try the following, note you have only 3 epochs and 4 figures, so the last axes is not formated

# constrained_layout  makes a nicer figure
fig1, axes1 = plt.subplots(rows, 2, constrained_layout=True)

epoch= [[11.0, 11.3, 11.4], [21.0, 22.0, 22.1], [98.0, 98.1, 98.2]] 
lst = iter(epoch)

for i in range(rows):
    for j in range(2):       
        axes1[i, j].plot(time, measurement)
        try:
            epoch = next(lst)
            axes1[i, j].set_xlim(min(epoch), max(epoch))
        except:
            print("no more epochs")
plt.show()

enter image description here

Answered By: Lucas M. Uriarte
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.