如何使用 matplotlib 创建一个大的子图? [英] How to use matplotlib to create a large graph of subplots?

查看:29
本文介绍了如何使用 matplotlib 创建一个大的子图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在遍历每个子图时遇到问题.我到达子图的坐标,然后希望每个子图上出现不同的模型.然而,我当前的解决方案循环遍历所有子图,但在每个子图中循环遍历所有模型,最后一个模型在每个子图中绘制,这意味着它们看起来都一样.

I am having trouble looping through each subplot. I reach the coordinates for the subplot, and then want different models to appear on each subplot. However, my current solution loops through all of the subplots, but at each one loops through all of the models, leaving the last model to be graphed at each subplot, meaning they all look the same.

我的目标是在每个子图上放置一个模型.请帮忙!

My goal is to place one model on every subplot. Please help!

modelInfo = csv_info(filename) # obtains information from csv file
f, axarr = plt.subplots(4, 6)
for i in range(4):
    for j in range(6):
        for model in modelInfo:
            lat = dictionary[str(model) + "lat"]
            lon = dictionary[str(model) + "lon"]
            lat2 = dictionary[str(model) + "lat2"]
            lon2 = dictionary[str(model) + "lon2"]
            axarr[i, j].plot(lon, lat, marker = 'o', color = 'blue')
            axarr[i, j].plot(lon2, lat2, marker = '.', color = 'red')
            axarr[i, j].set_title(model)

推荐答案

您可以将模型和轴zip 放在一起并同时循环遍历.但是,因为您的子图以 2d array 形式出现,您首先必须对其元素进行线性化".您可以通过对 numpy 数组使用 reshape 方法轻松地做到这一点.如果给该方法赋值 -1,它会将数组转换为 1d 向量.由于缺少输入数据,我使用 numpy 中的数学函数做了一个示例.有趣的 getattr 行只是为了让我能够轻松地为情节添加标题:

You can zip your models and axes together and loop over both at the same time. However, because your subplots come as a 2d array, you first have to 'linearize' its elements. You can easily do that by using the reshape method for numpy arrays. If you give that method the value -1 it will convert the array into a 1d vector. For lack of your input data, I made an example using mathematical functions from numpy. The funny getattr line is only there so that I was easily able to add titles to the plots:

from matplotlib import pyplot as plt
import numpy as np

modelInfo = ['sin', 'cos', 'tan', 'exp', 'log', 'sqrt']

f, axarr = plt.subplots(2,3)


x = np.linspace(0,1,100)
for model, ax in zip(modelInfo, axarr.reshape(-1)):
    func = getattr(np, model)
    ax.plot(x,func(x))
    ax.set_title(model)

f.tight_layout()
plt.show()

结果如下:.

请注意,如果您的模型数量超过可用subplots 的数量,多余的模型将被忽略且不会出现错误消息.

Note that, if your number of models exceeds the number of available subplots, the excess models will be ignored without error message.

希望这会有所帮助.

这篇关于如何使用 matplotlib 创建一个大的子图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆