A.Razavi
A.Razavi

Reputation: 509

Mapping subplots to axes in matplotlib

I would like to have a 3 by 3 subplots in matplotlib. Starting with this code, how can I set values of row_number and column_number automatically for each subplot?

    import matplotlib.pyplot as plt
    import numpy as np

    fig, axes = plt.subplots(ncols=3, nrows=3, figsize=(15, 15))
    for i in range(9):
        data = np.loadtxt('data_%d.txt' %i) 
        axes[row_number][column_number].plot(data)

Upvotes: 0

Views: 1171

Answers (2)

sbhhdp
sbhhdp

Reputation: 363

Not sure if this is what you meant.

enter image description here

Upvotes: 1

Paul H
Paul H

Reputation: 68116

Easiest way would be to enumerate a flattened array of axes:

import matplotlib.pyplot as plt
import numpy as np

fig, axes = plt.subplots(ncols=3, nrows=3, figsize=(15, 15))
for i, ax in enuermate(axes.flat):
    data = np.loadtxt('data_%d.txt' %i) 
    ax.plot(data)

Perhaps a more generalized what would be to glob your file objects and map them to a seaborn FacetGrid. This will let you process as many files as your want without having to compute how many rows your Axes grid will need. Since I don't know what your data look like, I've assumed some column names.

from pathlib import Path

from matplotlib import pyplot
import pandas
import seaborn

datadir = Path('~/location/of/your/data')

data = pandas.concat([
    pandas.read_csv(f, sep='\s+', names=['ydata']).assign(source=str(f.name))
    for f in datadir.glob('data_*.txt')
], ignore_index=True)

fg = seaborn.FacetGrid(data=data, col='source', col_wrap=3)
fg.map(pyplot.plot, y='ydata')

Upvotes: 1

Related Questions