Python Work

Posted by Atmospheric Chemistry & Satellite Remote Sensing on May 28, 2023

环境设置相关

import os
os.environ['PROJ_LIB'] = 'D:\anaconda3\pkgs\proj-7.0.0-haa36216_3\Library\share\proj'

数据读取相关

data = pd.read_csv("SURF_CLI_CHN_TEM_station.txt",sep='\s+',header=None, names=['station','lat','lon','high'])

sep='\s+' 指定每一列的间隔符是空格(正则表达)如果间隔是,的话那么sep=','即可
header=None 不读取文件头
names=['station','lat','lon','high'] 指定各列名称方便调用

画点线图相关命令

#生成一维数据
x = np.linspace(-1, 1, 20)
y = 2*x + 2
y_ = x**2
print(x, y)
 
#定义一个图像窗口  定义图像窗口编号,大小
fig = plt.figure()
ax  = fig.add_axes([0, 0, 0.7, 0.7])

############设置坐标轴的字体##################
label = ax.get_xticklabels() + ax.get_yticklabels()
[label.set_family( 'Helvetica') for label in label]
[label.set_size(14) for label in label]
############结束设置坐标轴的字体###############

#绘制点线图 定义图像上的点,曲线颜色,曲线宽度,曲线类型, 添加图例在右上角
plt.plot(x, y, marker='o', color='red', linewidth=2.0, linestyle='--', label='linear line')
plt.plot(x, y_, label='square line')
plt.legend(loc='upper right')

#设置x y坐标轴范围
plt.xlim( (-2, 4) )
plt.ylim( (-2, 4) )

#设置x y坐标轴名称
plt.xlabel('x')
plt.ylabel('y')

#设置x y坐标轴刻度
x_ticks = np.linspace(-1, 1, 5)
y_ticks = np.linspace(-1, 3, 5)
plt.xticks( x_ticks )
plt.yticks( y_ticks )

#添加文本注释
plt.text(-1,1,r'text info', fontdict={'size':16,'color':'r'})

#标题
plt.title("A simple plot")

Colorbar相关命令

# Colorbar settings
#下面定义colorbar大小和位置
# colorbar 左 下 宽 高
l = 0.95
b = 0.19
w = 0.03
h = 0.77
position=fig.add_axes([l, b, w, h])
cb = fig.colorbar(c,cax=position,orientation='vertical',extend='both', aspect=40)

#示例如下
position=fig.add_axes([0.18, 0.04, 0.01, 0.22])
cb = fig.colorbar(c,cax=position,orientation='vertical',extend='both')

position语句的4个参数分别定位: 第1个参数 离图片的间距
第2个参数 colorbar位置离图片下边界的距离
第3个参数 colorbar的宽度
第4个参数 colorbar的长度

设置标签,图例

ax.tick_params(which='both',labelsize=6,top=True,right=True,width=0.5)
ax.xaxis.set_major_formatter(cmt.LongitudeFormatter())
ax.yaxis.set_major_formatter(cmt.LatitudeFormatter())
ax.tick_params(axis='x', which='both', pad=0.5) # 调整下侧刻度线与图像之间的距离更紧凑
ax.tick_params(axis='y', which='both', pad=0.5) # 调整左侧刻度线与图像之间的距离更紧凑

legend_font = {
    'family': 'Helvetica',  # 字体
    'style': 'normal',
    'size': 11,  # 字号
    'weight': 'normal',  # 是否加粗
}
legend = ax.legend(loc='upper right',bbox_to_anchor = (0.1, 0.07, 0.9, 0.95),ncol = 1,labelspacing=0.5, frameon = True, shadow=False,prop = legend_font)

设置填色图投影方式,以及地图边界

proj = ccrs.PlateCarree()
leftlon, rightlon, lowerlat, upperlat = (-125,-113.8,33,42.3)
img_extent = [leftlon, rightlon, lowerlat, upperlat]

建立画布

fig = plt.figure(figsize=(20,15))
ax = fig.add_axes([0, 0, 0.17, 0.3],projection = proj)

点线图设置x和y轴上的小标签

ax.minorticks_on()
ax.xaxis.set_tick_params(which='major', direction="out",length=8, width=1)
ax.xaxis.set_tick_params(which='minor', direction="out",length=4, width=1)
ax.yaxis.set_tick_params(which='major', direction="out",length=8, width=1)
ax.yaxis.set_tick_params(which='minor', direction="out",length=4, width=1)

设置x和y轴上的标题

plt.xlabel('Year',family =  'Arial',size = 16,labelpad=3.0)
plt.ylabel('$\mathregular{PM_{2.5}}$ Conc. (μg/$\mathregular{m^{3}}$)',family = 'Arial',size = 16,labelpad=0)

设置图片标题

ax.set_title('(a) California',loc='left',size=12,fontdict = {'family' :  'Helvetica','weight' : 'bold'})

shape相关操作

shpfile = Reader(r'D:/python-scripts/MEGAN-ISOP-EF/shp/CaAirBasin_WGS1984.shp')
shape_feature1 = cfeature.ShapelyFeature(shpfile.geometries(),ccrs.PlateCarree(), facecolor='none',edgecolor='black',linewidths=0.3)
ax.add_feature(shape_feature1)    #添加shp地图

读取单个nc文件并绘图操作

isop = xr.open_dataset('D:/wkblog/python-scripts/MEGAN-ISOP-EF/EFMAPS.CA04.nc')
lons = isop['LONG'][0,0]
lats = isop['LAT'][0,0]
isop = isop['EF_ISOP'][0,0]
c = ax.pcolormesh(lons,lats,isop/1000,transform=ccrs.PlateCarree(),cmap=cmaps.WhiteGreen,vmin=0,vmax=5)

绘制点线图 定义图像上的点,曲线颜色,曲线宽度,曲线类型, 添加图例在右上角

plt.plot(x, y, marker='o', color='red', linewidth=2.0, linestyle='--', label='linear line')
plt.plot(x, y_, label='square line')
plt.legend(loc='upper right')