【问题标题】:Loop to create subplot /Python循环创建子图/Python
【发布时间】:2018-07-23 14:42:57
【问题描述】:

我在创建子图循环时遇到了一点问题。

下面的代码显示了我对一个图的结果....所以它从一个日循环开始,而不是一个小时循环(8 个时间步)。

如果我运行代码,我会得到一个漂亮的带有颜色条的 QUIver 图。

for dd in range(1,15):
  day=str(dd)
  readfile=fns[files_indizes[dd]]
  if dd < 10:
      nc_u_comp = NetCDFFile(ROOT+u_comp1+'0'+day+comp)
      nc_v_comp = NetCDFFile(ROOT+v_comp1+'0'+day+comp)
  else:
      nc_u_comp = NetCDFFile(ROOT+u_comp1+day+comp)
      nc_v_comp = NetCDFFile(ROOT+v_comp1+day+comp)

  time = nc_u_comp.variables['time'][:]

  index=readfile.find(comp)
  index=index+len(comp)
  date=readfile[index-14:index-6]
  plt.clf()

  for tt in range(0,len(time)):
      if tt < 10:
          h =str(0)+str(tt)
      else:
          h=str(tt)

      varU=nc_u_comp.variables['u10'][tt,:,:]
      varV=nc_v_comp.variables['v10'][tt,:,:]
      lat = nc_u_comp.variables['latitude'][:]
      lon = nc_u_comp.variables['longitude'][:]

      plt.rcParams["figure.figsize"] = [10,10]
      #plane projection of the world
      #map with box size (defintion on the top)
      box = sgeom.box(minx=llcrnrlon, maxx=urcrnrlon, miny=llcrnrlat, maxy=urcrnrlat)
      x0, y0, x1, y1 = box.bounds

      #Map plot. The middel of the map is central_longitude 
      #proj = ccrs.PlateCarree(central_longitude=0)
      proj=ccrs.PlateCarree()

      #Change middelpoint of the map
      box_proj = ccrs.PlateCarree(central_longitude=0)


      ax2 = plt.axes(projection=proj)
      ax2.set_extent([x0, x1, y0, y1], box_proj)
      ax2.add_feature(cartopy.feature.BORDERS, linestyle='-', alpha=.5)
      ax2.coastlines(resolution='50m')

      #Definition of the scale_bar
      gl = ax2.gridlines(ccrs.PlateCarree(), \
                      linestyle='--', alpha=1, linewidth=0.5, draw_labels=True)
      gl.xlabels_top = False
      gl.ylabels_right = False
      gl.xformatter = LONGITUDE_FORMATTER
      gl.yformatter = LATITUDE_FORMATTER

      magnitude = (varU ** 2 + varV ** 2) ** 0.5
      strm =plt.streamplot(lon , lat , varU, varV, linewidth=2, density=2, color=magnitude)
      cbar= plt.colorbar()
      cbar.set_label('$m/s$')
      name='Wind in 10 m '+ date + h+' UTC'
      ax2.set_aspect('auto')
      plt.title(name, y=1)

现在我想创建一个 2x4 的子图数组,并将颜色条分配给完整的子图数组。

我在互联网上找到了一些信息,但它不能与我的代码一起运行。也许有人可以帮助我?

【问题讨论】:

  • 您是在问如何使用 matplotlib 和 cartopy 创建子图吗? plt.subplot(3, 1, 3, projection=ccrs.PlateCarree()) 之类的东西是否符合您的要求(即标准的 matplotlib 函数,但带有 projection 关键字参数)?

标签: python loops cartopy


【解决方案1】:

这显示了如何在 4 行 2 列中绘制一组简单的 Cartopy 映射。还展示了如何绘制一个颜色条来伴随地图数组。希望对您有所帮助。

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

# create figure with figsize big enough to accomodate all maps, labels, etc.
fig = plt.figure(figsize=(8, 10), tight_layout=False)

# define plot array's arrangement
columns = 2
rows = 4
# set projection to use
projex = ccrs.PlateCarree()

# set the colormap and norm for
# the colorbar to use
cmap1 = mpl.cm.magma
norm1 = mpl.colors.Normalize(vmin=0, vmax=100)

def plotmymap(axs):
    # your plot specs of each map should replace this
    img = np.random.randint(100, size=(15, 30))  # 2d array of random values (1-100)
    # render image on current axis
    plims = plt.imshow(img, extent=[-180,180,-90,90], alpha=0.5, cmap=cmap1, norm=norm1)
    axs.set_global()
    axs.coastlines()
    # add title to the map
    axs.set_title("Map_"+str(i))
    return plims  # for use by colorbar

for i in range(1, columns*rows +1):
    # add a subplot into the array of plots
    ax = fig.add_subplot(rows, columns, i, projection=projex)
    plims = plotmymap(ax)  # a simple maps is created on subplot

# add a subplot for vertical colorbar
bottom, top = 0.1, 0.9
left, right = 0.1, 0.8
fig.subplots_adjust(top=top, bottom=bottom, left=left, right=right, hspace=0.15, wspace=0.25)
cbar_ax = fig.add_axes([0.85, bottom, 0.05, top-bottom])
fig.colorbar(plims, cax=cbar_ax)  # plot colorbar

plt.show()  # this plot all the maps

结果图:

【讨论】:

    猜你喜欢
    • 2022-07-07
    • 2014-05-18
    • 2013-09-24
    • 2015-08-18
    • 2020-07-23
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多