【问题标题】:How to use matplotlib to create a large graph of subplots?如何使用 matplotlib 创建子图的大图?
【发布时间】:2017-10-20 23:31:43
【问题描述】:

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

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

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)

【问题讨论】:

    标签: python matrix matplotlib plot subplot


    【解决方案1】:

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

    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 的数量,多余的模型将被忽略且不会出现错误消息。

    希望这会有所帮助。

    【讨论】:

    • 不错!比我一直做的好多了!
    • @GergesDib 你的也能完成这项工作,这是最重要的部分;)
    【解决方案2】:

    我认为这就是您正在寻找的,只要len(modelInfo) 小于6x4=24

    modelInfo = csv_info(filename) # obtains information from csv file
    f, axarr = plt.subplots(4, 6)
    
    for n, model in enumerate(modelInfo):
        i = int(n/4)
        j = n % 6 
        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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-26
      • 2021-09-21
      • 1970-01-01
      • 1970-01-01
      • 2011-03-24
      • 2022-12-06
      • 1970-01-01
      • 2020-05-05
      相关资源
      最近更新 更多