简体   繁体   English

将子图映射到 matplotlib 中的轴

[英]Mapping subplots to axes in matplotlib

I would like to have a 3 by 3 subplots in matplotlib.我想在 matplotlib 中有一个 3 x 3 的子图。 Starting with this code, how can I set values of row_number and column_number automatically for each subplot?从此代码开始,如何为每个子图自动设置row_numbercolumn_number的值?

    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.也许更通用的方法是将您的文件对象和 map 合并到 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.这将使您可以处理任意数量的文件,而无需计算 Axes 网格需要多少行。 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.不确定这是否是您的意思。

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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