import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.io.shapereader import Reader
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
def map():
plt.rcParams['font.sans-serif']=['SimHei'] #添加中文字体
plt.rcParams['axes.unicode_minus']=False #显示负号
fig = plt.figure(1,figsize=(40, 30))#设置图片尺寸
gs = matplotlib.gridspec.GridSpec(2, 1, height_ratios=[1, .02], bottom=.07, top=.99,hspace=0.01, wspace=0.01)
proj = ccrs.PlateCarree() # 简写投影
xticks = np.arange(117, 124, 2)#设置刻度范围精度
yticks = np.arange(25, 32, 2)
ax = fig.add_subplot(1,1,1, projection=proj)#子图行数、列数、位置
#ax.coastlines() #海岸线加粗
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=False,
linewidth=0.9, linestyle=':', color='k', alpha=0.8)#网格线设置
gl.xlocator = mticker.FixedLocator(xticks)
gl.ylocator = mticker.FixedLocator(yticks)
ax.set_xticks(xticks, crs=ccrs.PlateCarree())
ax.set_xticklabels(xticks, fontsize=40)
ax.set_yticks(yticks, crs=ccrs.PlateCarree())
ax.set_yticklabels(yticks, fontsize=40)
ax.xaxis.set_major_formatter(LongitudeFormatter(zero_direction_label=True))#x轴设为经度格式
ax.yaxis.set_major_formatter(LatitudeFormatter())#y轴设为经度格式
ax.add_feature(cfeature.OCEAN.with_scale('10m'))#高清地图
ax.add_feature(cfeature.LAND.with_scale('10m'))
ax.add_feature(cfeature.RIVERS.with_scale('10m'),lw=0.6)
ax.add_feature(cfeature.LAKES.with_scale('10m'))
ax.add_feature(cfeature.BORDERS.with_scale('50m'), linestyle='-',lw=0.6)
ax.add_feature(cfeature.COASTLINE.with_scale('10m'),lw=0.5)
# ax.scatter(120.84,27.91,marker='*',s=60, color = "r" , zorder = 4)#红色五角星标准机场位置 zorder控制五角星显示优先级
extent=[117.5,123.5,25,32.3] #设置绘图范围
shp_path=r'd:\shp\zhejiang_city.shp'
reader = Reader(shp_path)
provices = cfeature.ShapelyFeature(reader.geometries(), proj, edgecolor='k', facecolor='none')
ax.add_feature(provices, linewidth=2)#添加省界细节
ax.set_extent(extent)
if __name__ == '__main__':
global fig, ax, proj, gs
map()
如上所示,想创建一个地图函数,并在画图时直接引用其中的变量,在另一个程序中from map import ax, fig, gs, proj, 会报错,ImportError: cannot import name 'ax' from 'map' (D:\python_work\map.py),请问该如何解决。
建议你更换文件名称