Python海洋专题七之Cartopy画地形水深图的陆地填充

Python海洋专题七之Cartopy画地形水深图的陆地填充

第一期图

Python海洋专题七之Cartopy画地形水深图的陆地填充_第1张图片

本期:Python海洋专题七之Cartopy画地形水深图的陆地填充_第2张图片

上期

Cartopy画地形水深图

但是陆地没有填充

如图

Python海洋专题七之Cartopy画地形水深图的陆地填充_第3张图片

本期内容

陆地填充

如图:

Python海洋专题七之Cartopy画地形水深图的陆地填充_第4张图片

详细过程如下

1:陆地填充

land = feature.NaturalEarthFeature(‘physical’, ‘land’, scale, edgecolor=‘face’, facecolor=feature.COLORS[‘land’])
ax.add_feature(land, facecolor=‘0.6’)
Python海洋专题七之Cartopy画地形水深图的陆地填充_第5张图片

2:加岸线

ax.add_feature(feature.COASTLINE.with_scale(‘50m’),lw=0.4)
Python海洋专题七之Cartopy画地形水深图的陆地填充_第6张图片

问题

陆地填充了颜色,但是colorbar显示的数值还是包含陆地的高度!

解决

法一:改数据

直接把数据大于零的赋值为0.
ele = a.variables[‘elevation’][:]
ele[ele > 0] = 0
效果如图:

Python海洋专题七之Cartopy画地形水深图的陆地填充_第7张图片

法二:改代码

cf = ax.contourf(lon, lat, ele[:, :], levels=np.linspace(-9000,0,7),extend=‘both’,cmap=cmap_r1, transform=ccrs.PlateCarree())
效果如图:

图片
参考文献及其在本文中的作用

1:contourf的colorbar如何设置显示范围_colorbar颜色范围自定义-CSDN博客

往期内容

【python海洋专题一】查看数据nc文件的属性并输出属性到txt文件

【python海洋专题二】读取水深nc文件并水深地形图
【python海洋专题三】图像修饰之画布和坐标轴

【Python海洋专题四】之水深地图图像修饰

【Python海洋专题五】之水深地形图海岸填充

【Python海洋专题六】之Cartopy画地形水深图

【python海洋专题】测试数据

全文代码

法一

法一:# -*- coding: utf-8 -*-
# %%
# Importing related function packages
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as feature
import numpy as np
import matplotlib.ticker as ticker
from cartopy import mpl
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
from matplotlib.font_manager import FontProperties
from netCDF4 import Dataset
from palettable.cmocean.diverging import Delta_4
from palettable.colorbrewer.sequential import GnBu_9
from palettable.colorbrewer.sequential import Blues_9
from palettable.scientific.diverging import Roma_20
from pylab import *
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

cmap = Blues_9.mpl_colormap
cmap_r = reverse_colourmap(cmap)
cmap1 = GnBu_9.mpl_colormap
cmap_r1 = reverse_colourmap(cmap1)
cmap2 = Roma_20.mpl_colormap
cmap_r2 = reverse_colourmap(cmap2)
# read data
a = Dataset('D:\pycharm_work\data\scs_etopo.nc')
print(a)
lon = a.variables['lon'][:]
lat = a.variables['lat'][:]
ele = a.variables['elevation'][:]
ele[ele > 0] = 0
# plot
# 图三
# 设置地图全局属性
scale = '50m'
plt.rcParams['font.sans-serif'] = ['Times New Roman']  # 设置整体的字体为Times New Roman
fig = plt.figure(dpi=300, figsize=(3, 2), facecolor='w', edgecolor='blue')#设置一个画板,将其返还给fig
ax = fig.add_axes([0.05, 0.08, 0.92, 0.8], projection=ccrs.PlateCarree(central_longitude=180))
ax.set_extent([105, 125, 0, 25], crs=ccrs.PlateCarree()) # 设置显示范围
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.4)#添加海岸线:关键字lw设置线宽;linestyle设置线型
cf = ax.contourf(lon, lat, ele1[:, :], cmap=cmap_r1, transform=ccrs.PlateCarree())
# ------colorbar设置
cb=plt.colorbar(cf, ax=ax,extend='both', orientation='vertical')
cb.set_label('depth',fontsize= 4,color='k' )#设置colorbar的标签字体及其大小
cb.ax.tick_params(labelsize=4,direction='in') #设置colorbar刻度字体大小。
# 添加标题
ax.set_title('Etopo', fontsize=4)
# 利用Formatter格式化刻度标签
ax.set_xticks(np.arange(107, 125, 4), crs=ccrs.PlateCarree())#添加经纬度
ax.set_xticklabels(np.arange(107, 125, 4), fontsize=4)
ax.set_yticks(np.arange(0, 25, 2), crs=ccrs.PlateCarree())
ax.set_yticklabels(np.arange(0, 25, 2), fontsize=4)
ax.xaxis.set_major_formatter(LongitudeFormatter())
ax.yaxis.set_major_formatter(LatitudeFormatter())
ax.tick_params(color='k', direction='in')#更改刻度指向为朝内,颜色设置为蓝色
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=False, xlocs=np.arange(107, 125, 4), ylocs=np.arange(0, 25, 2),
        linewidth=0.25, linestyle='--', color='k', alpha=0.8)#添加网格线
gl.top_labels,gl.bottom_labels,gl.right_labels,gl.left_labels = False,False,False,False
plt.savefig('scs_elevation2.jpg', dpi=600, bbox_inches='tight', pad_inches=0.1)  # 输出地图,并设置边框空白紧密
plt.show()

法二

# -*- coding: utf-8 -*-
# %%
# Importing related function packages
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as feature
import numpy as np
import matplotlib.ticker as ticker
from cartopy import mpl
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
from matplotlib.font_manager import FontProperties
from netCDF4 import Dataset
from palettable.cmocean.diverging import Delta_4
from palettable.colorbrewer.sequential import GnBu_9
from palettable.colorbrewer.sequential import Blues_9
from palettable.scientific.diverging import Roma_20
from pylab import *
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

cmap = Blues_9.mpl_colormap
cmap_r = reverse_colourmap(cmap)
cmap1 = GnBu_9.mpl_colormap
cmap_r1 = reverse_colourmap(cmap1)
cmap2 = Roma_20.mpl_colormap
cmap_r2 = reverse_colourmap(cmap2)
# read data
a = Dataset('D:\pycharm_work\data\scs_etopo.nc')
print(a)
lon = a.variables['lon'][:]
lat = a.variables['lat'][:]
ele = a.variables['elevation'][:]
# ele[ele > 0] = 0
# plot
# 图三
# 设置地图全局属性
scale = '50m'
plt.rcParams['font.sans-serif'] = ['Times New Roman']  # 设置整体的字体为Times New Roman
fig = plt.figure(dpi=300, figsize=(3, 2), facecolor='w', edgecolor='blue')#设置一个画板,将其返还给fig
ax = fig.add_axes([0.05, 0.08, 0.92, 0.8], projection=ccrs.PlateCarree(central_longitude=180))
ax.set_extent([105, 125, 0, 25], crs=ccrs.PlateCarree())# 设置显示范围
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.4)#添加海岸线:关键字lw设置线宽;linestyle设置线型
cf = ax.contourf(lon, lat, ele[:, :], levels=np.linspace(-9000,0,7),extend='both',cmap=cmap_r1, transform=ccrs.PlateCarree())
# ------colorbar设置
cb = plt.colorbar(cf, ax=ax, extend='both', orientation='vertical')
cb.set_label('depth', fontsize=4, color='k')#设置colorbar的标签字体及其大小
cb.ax.tick_params(labelsize=4, direction='in') #设置colorbar刻度字体大小。

# 添加标题
ax.set_title('Etopo', fontsize=4)
# 利用Formatter格式化刻度标签
ax.set_xticks(np.arange(107, 125, 4), crs=ccrs.PlateCarree())#添加经纬度
ax.set_xticklabels(np.arange(107, 125, 4), fontsize=4)
ax.set_yticks(np.arange(0, 25, 2), crs=ccrs.PlateCarree())
ax.set_yticklabels(np.arange(0, 25, 2), fontsize=4)
ax.xaxis.set_major_formatter(LongitudeFormatter())
ax.yaxis.set_major_formatter(LatitudeFormatter())
ax.tick_params(color='k', direction='in')#更改刻度指向为朝内,颜色设置为蓝色
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=False, xlocs=np.arange(107, 125, 4), ylocs=np.arange(0, 25, 2),
        linewidth=0.25, linestyle='--', color='k', alpha=0.8)#添加网格线
gl.top_labels, gl.bottom_labels, gl.right_labels, gl.left_labels = False, False, False, False
plt.savefig('scs_elevation7.jpg', dpi=600, bbox_inches='tight', pad_inches=0.1)  # 输出地图,并设置边框空白紧密
plt.show()
图片

你可能感兴趣的:(python,人工智能,开发语言)