Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

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

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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: figure with different functions in different subplots.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...