python绘图记录
- 读取excel文件
- 将度分的经纬度转换为度
- 绘制填色图
- 两种添加网格线的方式
"""
Created on Mon Sep 19 10:32:00 2022
@author: Administrator
"""
import shapely.geometry as sgeom
import xarray as xr
import numpy as np
import matplotlib.pyplot as plt
import glob
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
import pandas as pd
import calendar
import os
import re
import matplotlib.ticker as mticker
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
path = r'D:/data_1.xlsx'
data = pd.read_excel(io=path,sheet_name='name')
lon = data['经度'].to_numpy()[1:]
lat = data['纬度'].to_numpy()[1:]
def convert_lon(lon):
if len(lon)==1:
a = float(lon[0:3])
b = float(lon[4:-1])
c = b/60
d = a + c
else:
d = np.zeros(lon.shape)
for i in range(len(lon)):
a1 = float(lon[i][0:3])
b1 = float(lon[i][4:-1])/60
d[i] = a1 + b1
return d
def convert_lat(lon):
if len(lon)==1:
a = float(lon[0:2])
b = float(lon[3:-1])
c = b/60
d = a + c
else:
d = np.zeros(lon.shape)
for i in range(len(lon)):
a1 = float(lon[i][0:2])
b1 = float(lon[i][3:-1])/60
d[i] = a1 + b1
return d
lon_new = convert_lon(lon)
lat_new = convert_lat(lat)
nc_path = r'D:/data2.nc'
ds = xr.open_dataset(nc_path)
depth = ds.bathymetry.sel(lat=slice(25,41),lon=slice(115,135))
depth_data =depth.data
depth_data[depth_data ==-10] = np.nan
plt.rcParams['axes.unicode_minus'] = False
fig = plt.figure(figsize=(8, 6), dpi=200)
proj = ccrs.PlateCarree()
ax = plt.axes(projection=ccrs.PlateCarree(central_longitude=180))
extents = [117.5,127,29.5,40.5]
ax.set_extent(extents, crs=proj)
ax.add_feature(cfeature.LAND, edgecolor='black',facecolor='silver',
)
ax.add_feature(cfeature.LAKES, edgecolor='black',facecolor='w',
)
ax.add_feature(cfeature.BORDERS)
xtick = np.arange(118, 128, 2)
ytick = np.arange(30,41, 1)
tick_proj = ccrs.PlateCarree()
ax.set_xticks(xtick, crs=tick_proj)
ax.set_xticks(xtick, crs=tick_proj)
ax.set_yticks(ytick, crs=tick_proj)
ax.set_yticks(ytick, crs=tick_proj)
ax.tick_params(which='major', direction='in',
length=3, width=0.4,
pad=0.2, bottom=True, left=True, right=False, top=False)
ax.xaxis.set_major_formatter(LongitudeFormatter())
ax.yaxis.set_major_formatter(LatitudeFormatter())
plt.yticks(fontproperties='Times New Roman',size=10)
plt.xticks(fontproperties='Times New Roman',size=10)
cmap=plt.get_cmap('RdYlBu')
ax.gridlines(linestyle='--',
xlocs=xtick,
ylocs=ytick,
x_inline=False,
y_inline=False,
zorder=2,
linewidth=0.5,
color='grey')
step=2
cb = ax.contourf(depth.lon,depth.lat,-depth_data,
transform=ccrs.PlateCarree(),
cmap=cmap,
levels=np.arange(-100,0+step,step),
zorder=2,
)
ac=ax.contour(-depth_data,colors='grey',
levels=np.arange(-100,0,20),
transform=ccrs.PlateCarree(),)
ax.clabel(ac)
ax.scatter(lon_new,lat_new,marker='s',s=10,
color='dimgray',
transform=ccrs.PlateCarree(),
zorder=2,
)
fig.colorbar(cb,
ticks=-np.array([0,10,20,30,40,50,60,70,80,90,100]),
label='Depth(m)')
plt.show()