python读取excel数据、转换度分为度,绘制填色图

python绘图记录

  • 读取excel文件
  • 将度分的经纬度转换为度
  • 绘制填色图
  • 两种添加网格线的方式
# -*- coding: utf-8 -*-
"""
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)
    
#### ======================================================================================
#### ===================================read_nc ==============================================
#### ======================================================================================

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  # 用来正常显示负号

#### ======================================================================================
#### ===================================draw ==============================================
#### ======================================================================================
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',
                # zorder=1,
               )
ax.add_feature(cfeature.LAKES, edgecolor='black',facecolor='w',
               # zorder=2
               )
ax.add_feature(cfeature.BORDERS)
# ax.add_feature(cfeature.NaturalEarthFeature('physical', 'land', '10m', \
#     edgecolor='k', facecolor='silver'))

# # 添加网格线
xtick = np.arange(118, 128, 2)
ytick = np.arange(30,41, 1)
# ax.coastlines()
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)

# # # # 利用Formatter格式化刻度标签
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(0,120+step,step),
            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',
           color='dimgray',
            transform=ccrs.PlateCarree(),
            zorder=2,
            )
fig.colorbar(cb,
             # shrink=0.9,
              ticks=-np.array([0,10,20,30,40,50,60,70,80,90,100]),
              label='Depth(m)')
plt.show()


# gl = ax.gridlines(
#                   linestyle='--', draw_labels=False,
#                   )
# gl.xlabels_top = False
# gl.ylabels_left = True
# gl.ylabels_right=False
# gl.xlines = True
# gl.xlocator = mticker.FixedLocator([118,120,122,124,126])
# gl.ylocator = mticker.FixedLocator([30,31,32,33,34,35,36,37,38,39,40])
# gl.xformatter = LONGITUDE_FORMATTER
# gl.yformatter = LATITUDE_FORMATTER
# gl.xlabel_style = {'color': 'black', 'weight': 'bold'}






  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

简朴-ocean

继续进步

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值