我在 matplotlib 中设置子图时遇到问题。下面是我想要实现的布局的屏幕截图。我只上过ax4,因为我遇到了两个问题。代码也在下面。(请注意,函数按预期绘制。)我想继续使用“subplot2grid”而不是其他选项,并且我使用的是 Python 2.7
预期行为: 地块 ax1、ax2 和 ax3 应该是世界阴影浮雕图,其位置如下面的所需布局所示。绘图 ax4 应该是一个散点图,其位置如下面的所需布局所示。
实际行为: 绘图 ax1、ax2 和 ax3 都是空白绘图 ax4 不是散点图,但它实际上是地图;布局也是错误的。
我以为我错过了“坚持”类型的功能,但看起来这不是 matplotlib 的工作方式。我还确保我在 myplotA 函数中定义了绘图限制。
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter
from mpl_toolkits.basemap import Basemap
from random import randint
def myplotA(plotnum, title):
south = 34.0129656032
north = 34.721878622
west = -116.7615176
east = -116.336918412
center = [(east + west) / 2, (north + south) / 2]
m = Basemap(llcrnrlon=west, llcrnrlat=south, urcrnrlon=east, urcrnrlat=north, resolution='c', epsg=4326, lon_0=center[0], lat_0=center[1], suppress_ticks=False)
img = m.arcgisimage(service="World_Shaded_Relief", xpixels=2000)
img.set_alpha(0.5)
plt.xticks(rotation='horizontal')
plotnum.xaxis.set_major_formatter(ScalarFormatter(useOffset=False))
plotnum.axis([west, east, south, north])
for label in (plotnum.get_xticklabels() + plotnum.get_yticklabels()):label.set_fontsize(9)
plt.gca().set_title(title, fontsize=12)
def myplotB(plotnum, title):
x = [randint(0, 10) for i in range(0, 6)]
y = [randint(0, 10) for i in range(0, 6)]
plotnum.scatter(x, y, s=4)
plotnum.xaxis.set_major_formatter(ScalarFormatter(useOffset=False))
plt.xlabel('xlabel', fontsize=8)
plt.ylabel('ylabel', fontsize=8)
plt.gca().set_title(title, fontsize=12)
fig = plt.figure(figsize=(11, 17))
ax1 = plt.subplot2grid((8, 3), (0, 0), rowspan=4, colspan=1)
ax2 = plt.subplot2grid((8, 3), (0, 1), rowspan=4, colspan=1)
ax3 = plt.subplot2grid((8, 3), (0, 2), rowspan=4, colspan=1)
ax4 = plt.subplot2grid((8, 3), (5, 0), rowspan=1, colspan=2)
myplotA(ax1, 'ax1')
myplotA(ax2, 'ax2')
myplotA(ax3, 'ax3')
myplotB(ax4, 'ax4')
plt.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=.1, hspace=.1)
fig.savefig(outpath + '\\' + 'mytest.pdf')
所需布局 所需布局图像
实际结果 实际结果图片