Adding subplots to a particular figure using "subplot2grid" method

时间:2017-08-30 20:06:29

标签: python matplotlib python-3.6

I am trying to add subplots of differing sizes to a particular matplotlib figure, and am unsure of how to do so. In the case of there only being one figure, the "subplot2grid" can be utilized as follows:

theme

The above code creates a figure, and adds two subplots to that figure, each with different dimensions. Now, my issue arises in the case of having multiple figures -- I cannot find the appropriate way to add subplots to a particular figure using "subplot2grid." Using the more simple "add_subplot" method, one can add subplots to a particular figure, as seen in the below code:

theme

I am looking for the analogous method for adding subplots of different sizes (preferably using some sort of grid manager, e.g. "subplot2grid") to a particular figure. I have reservations about using the plt."x" style because it operates on the last figure that was created -- my code will have several figures, all of which I will need to have subplots of different sizes.

Thanks in advance,

Curtis M.

1 个答案:

答案 0 :(得分:2)

将来(可能是即将发布的版本?),subplot2grid 将采用fig参数

subplot2grid(shape, loc, rowspan=1, colspan=1, fig=None, **kwargs)

以下是可能的:

import matplotlib.pyplot as plt

fig1=plt.figure()
fig2=plt.figure()

ax1 = plt.subplot2grid((2, 2), (0, 0), colspan=2, fig=fig1)
ax2 = plt.subplot2grid((2, 2), (1, 1),  fig=fig1)

plt.show()

截至目前(版本2.0.2),这还不可能。或者,您可以手动定义基础GridSpec

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

fig1=plt.figure()
fig2=plt.figure()

spec1 = GridSpec(2, 2).new_subplotspec((0,0), colspan=2)
ax1 = fig1.add_subplot(spec1)
spec2 = GridSpec(2, 2).new_subplotspec((1,1))
ax2 = fig1.add_subplot(spec2)

plt.show()

或者您可以简单地设置当前数字,这样plt.subplot2grid将对该确切数字起作用(如this question所示)

import matplotlib.pyplot as plt

fig1=plt.figure(1)
fig2=plt.figure(2)

# ... some other stuff

plt.figure(1) # set current figure to fig1
ax1 = plt.subplot2grid((2, 2), (0, 0), colspan=2)
ax2 = plt.subplot2grid((2, 2), (1, 1))

plt.show()