简体   繁体   中英

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)

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')

Not sure if this is what you meant.

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM