import numpy as npimport matplotlib.pyplot as pltfrom cartopy.mpl.ticker import LatitudeFormatter,LongitudeFormatterimport pandas as pd
def set_lat_or_lon_label(ax, lat_or_lon, x_or_y, delta_deg=None): """ parameter ------------- ax : matplotlib.axes (not geaxes) delta_deg : float, interval of longitude or latitude label x_or_y : 'x' or 'y' for x-axis (horizontal) and y-axis (vertial), respectively. lon_or_lat : 'lon' or 'lat'
In this function "xy" means "x or y". Made by Shoshiro Minobe """
if x_or_y=='x': xy_lim=ax.get_xlim() if x_or_y=='y': xy_lim=ax.get_ylim() xy_wid=xy_lim[1]-xy_lim[0]
xy_ticks=[] if lat_or_lon=='lat': for _lat in np.arange(0., 90.1, delta_deg): if xy_lim[0]<=_lat and _lat<=xy_lim[1]: xy_ticks.append(_lat) if xy_lim[0]<=-_lat and -_lat<=xy_lim[1] and _lat!=0: xy_ticks.append(-_lat) if lat_or_lon=='lon': for _lon in np.arange(0., 360.1, delta_deg): if xy_lim[0]<=_lon and _lon<=xy_lim[1]: xy_ticks.append(_lon) if xy_lim[0]<=-_lon and -_lon<=xy_lim[1] and _lon!=0: xy_ticks.append(-_lon)
xy_ticks.sort() print('xy_lim=',xy_lim) print(xy_ticks)
if lat_or_lon=='lon': lonfmt=LongitudeFormatter(zero_direction_label=True) if x_or_y=='x': ax.set_xticks(xy_ticks) ax.xaxis.set_major_formatter(lonfmt) if x_or_y=='y': ax.set_yticks(xy_ticks) ax.yaxis.set_major_formatter(lonfmt)
if lat_or_lon=='lat': latfmt=LatitudeFormatter() if x_or_y=='x': ax.set_xticks(xy_ticks) ax.xaxis.set_major_formatter(latfmt) if x_or_y=='y': ax.set_yticks(xy_ticks) ax.yaxis.set_major_formatter(latfmt)
ax.axes.tick_params(labelsize=10) return xy_ticks
xs1=np.arange(0, 360, 1)ts1=pd.date_range('2001-01-01',end='2001-12-31',freq='1D')ys1=np.arange(len(ts1))xsz=len(xs1)ysz=len(ys1)xs2d=np.ones([ysz,1]) @ xs1.reshape(1,xsz)ys2d=ys1.reshape(ysz,1) @ np.ones([1,xsz])zs1=np.cos(xs2d/180*np.pi) * np.cos(ys2d/90*np.pi)
ys2=np.arange(-90, 90.1, 1)ts2=pd.date_range('2001-01-01',end='2001-12-31',freq='1D')xs2=np.arange(len(ts2))xsz=len(xs2)ysz=len(ys2)xs2d=np.ones([ysz,1]) @ xs2.reshape(1,xsz)ys2d=ys2.reshape(ysz,1) @ np.ones([1,xsz])zs2=np.cos(xs2d/180*np.pi) * np.cos(ys2d/90*np.pi)
plt.ion()plt.clf()
ax=plt.subplot(2,2,1)ax.contourf(xs1,ts1,zs1)cartopy_helper.set_lat_or_lon_label(ax,'lon','x',delta_deg=60)
ax=plt.subplot(2,2,2)ax.contourf(ts1,xs1,zs1.T)cartopy_helper.set_lat_or_lon_label(ax,'lon','y',delta_deg=60)
ax=plt.subplot(2,2,3)ax.contourf(ys2,ts2,zs2.T)cartopy_helper.set_lat_or_lon_label(ax,'lat','x',delta_deg=30)
ax=plt.subplot(2,2,4)ax.contourf(ts2,ys2,zs2)cartopy_helper.set_lat_or_lon_label(ax,'lat','y',delta_deg=30)