Fbio Lds
Fbio Lds

Reputation: 13

How to plot sublots when creating plots in a for loop in python?

I'm new to programming and currently stuck on this: I create 4 different plots using a for loop and I want to assign each plot to a different subplot. Basically, I want 4 plots in a 2x2 grid so I can compare my data. Anyone knows how I can achieve this? My approach was to create a list of subplots and then assign every plot to a subplot using a nested plot:

import matplotlib.pyplot as plt
import numpy as np

def load_file(filename):
    return np.loadtxt(filename, delimiter=',', usecols=(0, 1), unpack=True, skiprows=1)


fig = plt.figure()

ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)

ax_list=[ax1, ax2, ax3, ax4]

for i,filename in enumerate(file_list):
    for p in ax_list:
        x,y = load_file(filename)
        plt.plot(x,y,
        label=l, #I assign labels from a list beforehand, as well as colors
        color=c,
        linewidth=0.5,
        ls='-',
               )
        p.plot()

The problem is, all plots are assigned to only one subplot and I don't know how to correct this. I'd appreciate any help!

Upvotes: 0

Views: 4297

Answers (2)

Ken Syme
Ken Syme

Reputation: 3632

You don't need to loop over filenames and plots, only need to select the next plot in the list.

for i, filename in enumerate(file_list):
    p = ax_list[i]:
    x,y = load_file(filename)
    p.plot(x, y,
        label=l, #I assign labels from a list beforehand, as well as colors
        color=c,
        linewidth=0.5,
        ls='-')

plt.plot()

You can also replace

fig = plt.figure()

ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)

ax_list=[ax1, ax2, ax3, ax4]

with just

fig, ax_list = plt.subplots(2, 2)
ax_list = ax_list.flatten()

To get a simple 2x2 grid.

Upvotes: 0

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339230

I guess what you want is to show different data on all 4 plots, hence use a single loop. Make sure to use the axes plotting method, not plt.plot as the latter would always plot in the last subplot.

import matplotlib.pyplot as plt
import numpy as np

def load_file(filename):
    return np.loadtxt(filename, delimiter=',', usecols=(0, 1), unpack=True, skiprows=1)

fig, ax_list = plt.subplots(2,2)

for i,(filename,ax) in enumerate(zip(file_list, ax_list.flatten())):
    x,y = load_file(filename)
    ax.plot(x,y, linewidth=0.5,ls='-' )
plt.show()

Upvotes: 1

Related Questions