How to use matplotlib to create a large graph of subplots?

情到浓时终转凉″ 提交于 2019-11-26 21:43:56

问题


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)

回答1:


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: .

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

Hope this helps.




回答2:


I think this is what you are looking for, which works as long as len(modelInfo) is less than 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)


来源:https://stackoverflow.com/questions/44093705/how-to-use-matplotlib-to-create-a-large-graph-of-subplots

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!