-1

I want to make subplots in a for-loop. This is integrated in a larger code. I have multiple csv files containing various x values and fixed y values for all the files. The shape of each file is the same. For instance, it looks like the followings: Data set #1.

y   x1   x2   x3   x4
1  0.2  5.4  3.0  0.7
2  0.1  1.2  4.0  0.6
3  5.0  2.0  2.0  1.8
4  1.2  0.1  0.1  3.8
5  1.0  0.5  0.7  5.8
6  6.5  8.0  0.8  0.8

The x values in each data are complied: my_xdata=[array([0.2,0.1,5.0,1.2,1.0,6.5],[5.4,1.2,2.0,0.1,0.5,8.0],[3.0,4.0,2.0,0.1,0.7,0.8], [0.7,0.6,1.8,3.8,5.8,0.8)]

My desired outcome is subplots plotting x1 and y, x2 and y, x3 and y and x4 and y. But currently, the code is not working. The following is the code that I currently have.

for i in range(len(my_xdata)):
     for a in range(len(specific_x)):
         ax=plt.subplot(4,1,i+1)
         ax.plot(my_y,my_xdata[i])
         ax.set_xlim(15,70)
         ax.axhline(y=0.1, linestyle='--', color='k')
         ax.axhline(y=0.5, linestyle='--', color='k')
         ax.axhline(y=0.9, linestyle='--', color='k')
         ax.axvline(x=median_ten1[a], linestyle='--', color='k')
         ax.axvline(x=median_fifty1[a], linestyle='--', color='k')
         ax.axvline(x=median_ninety1[a], linestyle='--', color='k')
         ax.show()

It doesn't work.

I get the following error message, num must be 1 <= num <= 4, not 5. Any ideas?

specific_x isn't that important, but if you want to know. Here it is:

for i in range(len(my_xdata)):
   f90= interp1d(my_xdata[i], my_y, assume_sorted = False) #interpolate the x values 
   specific_x.append(f90(1.2)) #determine the x values when y is 1.2
user7852656
  • 675
  • 4
  • 15
  • 26

1 Answers1

0

Couldn't reproduce the error message, plotting in subplots with a for loop works quite fine. I used the following code to test:

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d

my_xdata=np.array([[0.2,0.1,5.0,1.2,1.0,6.5],[5.4,1.2,2.0,0.1,0.5,8.0],[3.0,4.0,2.0,0.1,0.7,0.8],[0.7,0.6,1.8,3.8,5.8,0.8]])
my_y = np.array([10,20,30,40,50,60])

specific_x = []
for i in range(len(my_xdata)):
   f90= interp1d(my_xdata[i], my_y, assume_sorted = False) #interpolate the x values 
   specific_x.append(f90(1.2)) #determine the x values when y is 1.2


for i in range(len(my_xdata)):
     for a in range(len(specific_x)):
         ax=plt.subplot(4,1,i+1)
         ax.plot(my_y,my_xdata[i])
         ax.set_xlim(15,70)
         ax.axhline(y=0.1, linestyle='--', color='k')
         ax.axhline(y=0.5, linestyle='--', color='k')
         ax.axhline(y=0.9, linestyle='--', color='k')
#         ax.axvline(x=median_ten1[a], linestyle='--', color='k')
#         ax.axvline(x=median_fifty1[a], linestyle='--', color='k')
#         ax.axvline(x=median_ninety1[a], linestyle='--', color='k')
         #ax.show()

matplotlib output 4 subplots

Qvyx
  • 38
  • 4