在Python中生成子批时调用其他函数

2024-05-18 21:04:49 发布

您现在位置:Python中文网/ 问答频道 /正文

更新:我现在可以在正确的位置获得子批次,并显示正确的数据!但是,还有一个问题,那就是我不能给子图赋予它们自己的标题和颜色栏。实际上,我宁愿在所有情节的右边只有一个色条,但这似乎也不起作用。下面是我的新代码以及一些示例数据(with是非常不重要的,但只是为了测试目的):

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import cartopy.crs as ccrs

lons = np.arange(-180,180,1)
lats = np.arange(-80,80,1)
dens = np.zeros((12, len(lons), len(lats)))
for i in range(12):
   dens[i,:,:] = i

def plotTitle(yr):
   letter = chr(yr-2002+97)
   return '(' + letter + ') ' + str(yr)

def DensityPlot(yr, lon, lat, dens, ax):
   Lat, Lon = np.meshgrid(lat, lon)
   density = ax.pcolormesh(Lon, Lat, dens, cmap = 'jet')
   #cbar = ax.colorbar(density, orientation='vertical', shrink=0.5, extend='both') # this gives an error: ''GeoAxesSubplot' object has no attribute 'colorbar''
   ax.coastlines()
   plt.title(plotTitle(yr),fontsize=14,fontweight='bold') # this only works for the last plot. ax.title doesn't work, gives the error ''Text' object is not callable'

fig, axes = plt.subplots(nrows=6, ncols=2, figsize=(35,35), subplot_kw={'projection': ccrs.PlateCarree()}) ## check figsize
i=0
for ax in axes.flat:
   densdata = dens[i,:,:]
   density = DensityPlot(i+2002, lons, lats, densdata, ax)
   i=i+1
   #ax.title(plotTitle(i+2002)) # this gives the same error as mentioned before: ''Text' object is not callable'
#cbar = plt.colorbar(density, orientation='vertical', shrink=0.5, extend='both')
# this gives the following RuntimeError: No mappable was found to use for colorbar creation. First define a mappable such as an image (with imshow) or a contour set (with contourf).
fig.subplots_adjust(right=0.5)

如何确保每个子批次都有自己的标题,并且在所有子批次旁边都有一个颜色栏?在


我在Python中创建一组子批时遇到了一个问题。我定义了一个生成特定绘图的函数:

^{pr2}$

现在我想在for循环中使用这个函数来生成子批。为了简单起见,我们假设我可以在每个子图中对latlon和{}使用相同的值(因此我只需要多次获得相同的图)。但是,以下代码将不起作用:

fig, axes = plt.subplots(nrows=6, ncols=2)
for j in range(0,12): 
   plt.subplot(6,2,j+1)
   density = DensityPlot(lon, lat, dens)

发生以下情况:首先,显示12个空绘图,尽管它们的顺序正确(6x2)。在那之后,11个空的图块出现在彼此下面,最后最后一个图实际上是按照它应该显示的方式显示的。我已经检查了函数DensityPlot的代码来创建单个绘图,并且知道它可以很好地完成这项工作,所以问题肯定出在子图创建中。这里有什么问题,我该怎么解决?在


Tags: importforasnppltaxthisdensity
1条回答
网友
1楼 · 发布于 2024-05-18 21:04:49

您自己怀疑它,您在循环之外创建子批,但是每次调用函数时都会创建一个新的图。在

应首先使用所需的投影创建图形和轴:

fig, axes = plt.subplots(nrows=6, ncols=2, subplot_kw={'projection': ccrs.PlateCarree()})

然后可以循环轴,并将其作为参数传递给函数(确保删除图形本身中的任何图形或轴创建):

^{pr2}$

为了给每个子批次添加标题,您需要在函数中使用ax.set_title()

ax.set_title(plotTitle(yr))

对于为多个子图添加颜色条还有许多其他问题。例如Matplotlib 2 Subplots, 1 Colorbar

相关问题 更多 >

    热门问题