如何使用matplotlib创建大的子图图

如何使用matplotlib创建大的子图图

本文介绍了如何使用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()

结果看起来像这样:.

The result looks like this:.

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

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

希望这会有所帮助.

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

08-11 16:09