[python ocean topic twenty-two] text on the chart

There were four sub-pictures in the last issue

But I want to mark A, B, C, D or spring, summer, autumn and winter

Contents of this issue

text on chart

1: The effect is as shown in the figure

Unmarked

picture

mark

Picture

key statement

# Add text comments
ax.text(104, 22, 'autumn', fontdict={'family': 'serif', 'size': 4, 'color': 'blue'}, ha='center', va='center', transform=ccrs.PlateCarree())

Recommended in the past

[Python Ocean Topic 1] View the attributes of the data nc file and output the attributes to the txt file

[Python Ocean Topic 2] Read the water depth nc file and read the water depth topographic map
[Python Ocean Topic 3] Image modification canvas and coordinate axes

[Python Ocean Topic 4] Depth Map Image Modification

[Python Ocean Topic 5] Water Depth Topography Map Coastal Filling

[Python Ocean Topic 6] Cartopy draws terrain and water depth maps

[python ocean topic] test data

[Python Ocean Topic 7] Cartopy draws land filling of topographic and bathymetric maps

[Python Ocean Topic 8] Cartopy adjusts the number of contourf filling intervals for drawing topographic and bathymetric maps

[Python Ocean Topic 9] Cartopy draws terrain contour maps

[Python Ocean Topic 10] Cartopy draws terrain contour maps of specific areas

[Python Ocean Topic 11] Colormap Color Adjustment

[Python Ocean Topic 12] Annual average sea surface temperature map of the South China Sea

[Python Ocean Topic 13] Read multiple nc files to draw seasonal changes in temperature

[Python Ocean Topic 14] Read multiple salinity NC data and draw seasonal changes in salinity

[Python Ocean Topic 15] Add units to colorbar

[Python Ocean Topic 16] Proximity interpolation of data around the continent

[Python Ocean Topic Seventeen] Read decades of OHC data and draw four-season charts

[Python Ocean Topic 18] Read the Soda data and draw a subplot of the seasonal changes in sea surface height.

[Python Ocean Topic 19] Advanced version of statement to find range

[Python Ocean Topic 20] subplots_adjust layout adjustment

Full text code

# -*- coding: utf-8 -*-
# ---Import modules for data reading and processing-------
from netCDF4 import Dataset
from pathlib import Path
import xarray as xr
import numpy as np
# ------Import drawing related functions--------
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
import matplotlib.ticker as ticker
from cartopy import mpl
import cartopy.crs as ccrs
import cartopy.feature as feature
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
from pylab import *
# -----Import color pack---------
import seaborn as sns
from matplotlib import cm
import paletable
from palettable.cmocean.diverging import Delta_4
from palettable.colorbrewer.sequential import GnBu_9
from paletable.colorbrewer.sequential import Blues_9
from paletable.scientific.diverging import Roma_20
from palettable.cmocean.diverging import Delta_20
from paletable.scientific.diverging import Roma_20
from palettable.cmocean.diverging import Balance_20
from matplotlib.colors import ListedColormap
# -------Import interpolation module-----
from scipy.interpolate import interp1d #Introduce the one-dimensional interpolation library in scipy
from scipy.interpolate import griddata #Introduce the two-dimensional interpolation library in scipy
from scipy.interpolate import interp2d


# ----define reverse_colourmap defines the reverse function of color----
def reverse_colourmap(cmap, name='my_cmap_r'):
    reverse = []
    k = []


    for key in cmap._segmentdata:
        k.append(key)
        channel = cmap._segmentdata[key]
        data = []


        for t in channel:
            data.append((1 - t[0], t[2], t[1]))
        reverse.append(sorted(data))


    LinearL = dict(zip(k, reverse))
    my_cmap_r = mpl.colors.LinearSegmentedColormap(name, LinearL)
    return my_cmap_r




# ---Reading and reverse of colormap----
cmap01 = Balance_20.mpl_colormap
cmap0 = Blues_9.mpl_colormap
cmap_r = reverse_colourmap(cmap0)
cmap1 = GnBu_9.mpl_colormap
cmap_r1 = reverse_colourmap(cmap1)
cmap2 = Roma_20.mpl_colormap
cmap_r2 = reverse_colourmap(cmap2)
# ---read_data---
f1 = xr.open_dataset(r'E:\data\soda\soda3.12.2_5dy_ocean_reg_2017.nc')
print(f1)
# # Extract latitude and longitude (so no need to read repeatedly)
lat = f1['yt_ocean'].data
lon = f1['xt_ocean'].data
ssh = f1['ssh'].data
time = f1['time'].data
print(time)
# # -------- find scs 's temp -----------
ln1 = np.where(lon >= 100)[0][0]
ln2 = np.where(lon >= 125)[0][0]
la1 = np.where(lat >= 0)[0][0]
la2 = np.where(lat >= 25)[0][0]
# # # Drawing grid
lon1 = lon[ln1:ln2]
lat1 = lat[la1:la2]
X, Y = np.meshgrid(lon1, lat1)
ssh_aim = ssh[:, la1:la2, ln1:ln2]
# # ----------Average the time dimension to get the ssh of spring, summer, autumn and winter------------------
ssh_spr_mean = np.mean(ssh_aim[2:5, :, :], axis=0)
ssh_sum_mean = np.mean(ssh_aim[5:8, :, :], axis=0)
ssh_atu_mean = np.mean(ssh_aim[8:11, :, :], axis=0)
ssh_win_mean = (ssh_aim[0, :, :] + ssh_aim[1, :, :] + ssh_aim[11, :, :])/3
# # -------------# plot ------------
scale = '50m'
plt.rcParams['font.sans-serif'] = ['Times New Roman'] # Set the overall font to Times New Roman
fig = plt.figure(dpi=300, figsize=(3, 2), facecolor='w', edgecolor='blue') # Set up a drawing board and return it to fig
# --------The first sub-picture----------
ax = fig.add_subplot(2, 2, 1, projection=ccrs.PlateCarree(central_longitude=180))
ax.set_extent([100, 125, 0, 25], crs=ccrs.PlateCarree()) # Set the display range
land = feature.NaturalEarthFeature('physical', 'land', scale, edgecolor='face',
                                   facecolor=feature.COLORS['land'])
ax.add_feature(land, facecolor='0.6')
ax.add_feature(feature.COASTLINE.with_scale('50m'), lw=0.3) # Add coastline: keyword lw sets line width; lifestyle sets line style
cs = ax.contourf(X, Y, ssh_spr_mean, extend='both', cmap=cmap_r2, levels=np.linspace(0, 1, 50),
                 transform=ccrs.PlateCarree()) #
# ------color-bar settings------------
cb = plt.colorbar(cs, ax=ax, extend='both', orientation='vertical', ticks=[0, 0.2, 0.4, 0.6, 0.8, 1.0]) #
# cb.set_label('SSH', fontsize=4, color='k') # Set the color-bar label font and size
cb.ax.tick_params(labelsize=4, direction='in', length=1.5, color='k') # Set the color-bar tick font size.
# -----------------Add title----------------
# ax.set_title('SSH', fontsize=4)
# ------------------Use Formatter to format tick labels-----------------
ax.set_xticks(np.arange(100, 126, 5), crs=ccrs.PlateCarree()) #Add latitude and longitude
ax.set_xticklabels(np.arange(100, 126, 5), fontsize=4)
ax.set_yticks(np.arange(0, 26, 5), crs=ccrs.PlateCarree())
ax.set_yticklabels(np.arange(0, 26, 5), fontsize=4)
ax.xaxis.set_major_formatter(LongitudeFormatter())
ax.yaxis.set_major_formatter(LatitudeFormatter())
ax.tick_params(axis='x', top=True, which='major', direction='in', length=2, width=0.8, labelsize=4, pad=1,
               color='k') # Scale style
ax.tick_params(axis='y', right=True, which='major', direction='in', length=2, width=0.8, labelsize=4, pad=1,
               color='k') # Change the scale pointing inwards and set the color to blue
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=False, xlocs=np.arange(100, 126, 5), ylocs=np.arange(0, 26, 5),
                  linewidth=0.25, linestyle='--', color='k', alpha=0.8) # Add grid lines
gl.top_labels, gl.bottom_labels, gl.right_labels, gl.left_labels = False, False, False, False
ax.text(104, 22, 'spring', fontdict={'family': 'serif', 'size': 4, 'color': 'blue'}, ha='center', va='center', transform=ccrs.PlateCarree())


# --------The second sub-picture----------
ax = fig.add_subplot(2, 2, 2, projection=ccrs.PlateCarree(central_longitude=180))
ax.set_extent([100, 125, 0, 25], crs=ccrs.PlateCarree()) # Set the display range
land = feature.NaturalEarthFeature('physical', 'land', scale, edgecolor='face',
                                   facecolor=feature.COLORS['land'])
ax.add_feature(land, facecolor='0.6')
ax.add_feature(feature.COASTLINE.with_scale('50m'), lw=0.3) # Add coastline: keyword lw sets line width; lifestyle sets line style
cs = ax.contourf(X, Y, ssh_sum_mean, extend='both', cmap=cmap_r2, levels=np.linspace(0, 1, 50),
                 transform=ccrs.PlateCarree()) #
# ------color-bar settings------------
cb = plt.colorbar(cs, ax=ax, extend='both', orientation='vertical', ticks=[0, 0.2, 0.4, 0.6, 0.8, 1.0]) #
# cb.set_label('SSH', fontsize=4, color='k') # Set the color-bar label font and size
cb.ax.tick_params(labelsize=4, direction='in', length=1.5, color='k') # Set the color-bar tick font size.
# -----------------Add title----------------
# ax.set_title('SSH', fontsize=4)
# ------------------Use Formatter to format tick labels-----------------
ax.set_xticks(np.arange(100, 126, 5), crs=ccrs.PlateCarree()) #Add latitude and longitude
ax.set_xticklabels(np.arange(100, 126, 5), fontsize=4)
ax.set_yticks(np.arange(0, 26, 5), crs=ccrs.PlateCarree())
ax.set_yticklabels(np.arange(0, 26, 5), fontsize=4)
ax.xaxis.set_major_formatter(LongitudeFormatter())
ax.yaxis.set_major_formatter(LatitudeFormatter())
ax.tick_params(axis='x', top=True, which='major', direction='in', length=2, width=0.8, labelsize=4, pad=1,
               color='k') # Scale style
ax.tick_params(axis='y', right=True, which='major', direction='in', length=2, width=0.8, labelsize=4, pad=1,
               color='k') # Change the scale pointing inwards and set the color to blue
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=False, xlocs=np.arange(100, 126, 5), ylocs=np.arange(0, 26, 5),
                  linewidth=0.25, linestyle='--', color='k', alpha=0.8) # Add grid lines
gl.top_labels, gl.bottom_labels, gl.right_labels, gl.left_labels = False, False, False, False
ax.text(104, 22, 'summer', fontdict={'family': 'serif', 'size': 4, 'color': 'blue'}, ha='center', va='center', transform=ccrs.PlateCarree())
# --------The third sub-picture----------
ax = fig.add_subplot(2, 2, 3, projection=ccrs.PlateCarree(central_longitude=180))
ax.set_extent([100, 125, 0, 25], crs=ccrs.PlateCarree()) # Set the display range
land = feature.NaturalEarthFeature('physical', 'land', scale, edgecolor='face',
                                   facecolor=feature.COLORS['land'])
ax.add_feature(land, facecolor='0.6')
ax.add_feature(feature.COASTLINE.with_scale('50m'), lw=0.3) # Add coastline: keyword lw sets line width; lifestyle sets line style
cs = ax.contourf(X, Y, ssh_atu_mean, extend='both', cmap=cmap_r2, levels=np.linspace(0, 1, 50),
                 transform=ccrs.PlateCarree()) #
# ------color-bar settings------------
cb = plt.colorbar(cs, ax=ax, extend='both', orientation='vertical', ticks=[0, 0.2, 0.4, 0.6, 0.8, 1.0]) #
# cb.set_label('SSH', fontsize=4, color='k') # Set the color-bar label font and size
cb.ax.tick_params(labelsize=4, direction='in', length=1.5, color='k') # Set the color-bar tick font size.
# -----------------Add title----------------
# ax.set_title('SSH', fontsize=4)
# ------------------Use Formatter to format tick labels-----------------
ax.set_xticks(np.arange(100, 126, 5), crs=ccrs.PlateCarree()) #Add latitude and longitude
ax.set_xticklabels(np.arange(100, 126, 5), fontsize=4)
ax.set_yticks(np.arange(0, 26, 5), crs=ccrs.PlateCarree())
ax.set_yticklabels(np.arange(0, 26, 5), fontsize=4)
ax.xaxis.set_major_formatter(LongitudeFormatter())
ax.yaxis.set_major_formatter(LatitudeFormatter())
ax.tick_params(axis='x', top=True, which='major', direction='in', length=2, width=0.8, labelsize=4, pad=1,
               color='k') # Scale style
ax.tick_params(axis='y', right=True, which='major', direction='in', length=2, width=0.8, labelsize=4, pad=1,
               color='k') # Change the scale pointing inwards and set the color to blue
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=False, xlocs=np.arange(100, 126, 5), ylocs=np.arange(0, 26, 5),
                  linewidth=0.25, linestyle='--', color='k', alpha=0.8) # Add grid lines
gl.top_labels, gl.bottom_labels, gl.right_labels, gl.left_labels = False, False, False, False
#Add text comment
ax.text(104, 22, 'autumn', fontdict={'family': 'serif', 'size': 4, 'color': 'blue'}, ha='center', va='center', transform=ccrs.PlateCarree())


# --------The fourth sub-picture----------
ax = fig.add_subplot(2, 2, 4, projection=ccrs.PlateCarree(central_longitude=180))
ax.set_extent([100, 125, 0, 25], crs=ccrs.PlateCarree()) # Set the display range
land = feature.NaturalEarthFeature('physical', 'land', scale, edgecolor='face',
                                   facecolor=feature.COLORS['land'])
ax.add_feature(land, facecolor='0.6')
ax.add_feature(feature.COASTLINE.with_scale('50m'), lw=0.3) # Add coastline: keyword lw sets line width; lifestyle sets line style
cs = ax.contourf(X, Y, ssh_win_mean, extend='both', cmap=cmap_r2, levels=np.linspace(0, 1, 50),
                 transform=ccrs.PlateCarree()) #
#Add text comment
ax.text(104, 22, 'Winter', fontdict={'family': 'serif', 'size': 4, 'color': 'blue'}, ha='center', va='center', transform=ccrs.PlateCarree())
# ------color-bar settings------------
cb = plt.colorbar(cs, ax=ax, extend='both', orientation='vertical', ticks=[0, 0.2, 0.4, 0.6, 0.8, 1.0]) #
# cb.set_label('SSH', fontsize=4, color='k') # Set the color-bar label font and size
cb.ax.tick_params(labelsize=4, direction='in', length=1.5, color='k') # Set the color-bar tick font size.
# -----------------Add title----------------
# ax.set_title('SSH', fontsize=4)
# ------------------Use Formatter to format tick labels-----------------
ax.set_xticks(np.arange(100, 126, 5), crs=ccrs.PlateCarree()) #Add latitude and longitude
ax.set_xticklabels(np.arange(100, 126, 5), fontsize=4)
ax.set_yticks(np.arange(0, 26, 5), crs=ccrs.PlateCarree())
ax.set_yticklabels(np.arange(0, 26, 5), fontsize=4)
ax.xaxis.set_major_formatter(LongitudeFormatter())
ax.yaxis.set_major_formatter(LatitudeFormatter())
ax.tick_params(axis='x', top=True, which='major', direction='in', length=2, width=0.8, labelsize=4, pad=1,
               color='k') # Scale style
ax.tick_params(axis='y', right=True, which='major', direction='in', length=2, width=0.8, labelsize=4, pad=1,
               color='k') # Change the scale pointing inwards and set the color to blue
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=False, xlocs=np.arange(100, 126, 5), ylocs=np.arange(0, 26, 5),
                  linewidth=0.25, linestyle='--', color='k', alpha=0.8) # Add grid lines
gl.top_labels, gl.bottom_labels, gl.right_labels, gl.left_labels = False, False, False, False
# -------Add a large title for the subpicture--------
plt.suptitle("SSH", fontsize=6, color='red')
plt.savefig('SSH_2.jpg', dpi=600, bbox_inches='tight', pad_inches=0.1) # Output the map and set the border margin to be tight
plt.show()