How do i iterate my dataframe values to create subplots?

Viewed 57

Hello all im trying to create a 11X2 subplot by iterating the columns that i have.

here is a snapshot of my dataframe. There are n units (100 actually) where each units have i amount of cycles. enter image description here

The regression of sensor S7 for every unit combined looks like this: enter image description here

, it is achieved by this:

for i in range(1,101):
    plt.plot(df[df.unit==i].cycles, df[df.unit==i].S7)
plt.ylabel('Sensor measurements')
plt.xlabel('# cycles')

I'd like to create a subplot to show all the sensors. I have attempted by using iteration but it doesnt work.

sensors = ["Op1", "Op2", "Op3", "S2", "S3", "S4", "S5", "S6", "S7", "S8", "S9", "S10", "S11",
           "S12", "S13", "S14", "S15", "S16", "S17", "S18", "S19", "S20", "S21"]
i = 1
for sensor in sensors:
    for n in range(1,101):
        plt.subplot(len(sensors), 1, i)
        plt.plot(df[df.unit==n].cycles, df[df.unit==n].sensor)
    i += 1

What are the changes I should apply to my code? Thank you so much

1 Answers

You can create a list of subplots first, and plot into them:

fig, axes = plt.subplots(2, 11)   # change these numbers as wished

for sensor, ax in zip(sensors, axes.ravel()):
    for n in range(1,101):
        df[df.unit==n].plot(x='cycles', y=sensor, ax=ax)
        ax.set_title(sensor)

        # remove the long legend
        ax.legend().remove()
Related