Python是一种强大的编程语言,可以用于多种应用程序。本文将介绍如何使用Python绘制平面地图。
# 导入必要的库 import matplotlib.pyplot as plt import numpy as np # 创建地图 def create_map(): fig, ax = plt.subplots() ax.set_xlim([-180, 180]) ax.set_ylim([-90, 90]) ax.set_xticks(np.arange(-180, 181, 30)) ax.set_yticks(np.arange(-90, 91, 30)) ax.xaxis.set_ticklabels([]) ax.yaxis.set_ticklabels([]) ax.grid(True, which='both') return fig, ax # 绘制国界线 def draw_boundary(ax, boundary_file): with open(boundary_file, 'r') as f: boundary_lines = f.readlines() for line in boundary_lines: points = line.strip().split(',') x, y = float(points[0]), float(points[1]) ax.plot(x, y, 'k', linewidth=0.5) # 绘制城市 def draw_cities(ax, city_file): with open(city_file, 'r') as f: city_lines = f.readlines() for line in city_lines: city_info = line.strip().split(',') city_name, city_lon, city_lat = city_info[0], float(city_info[1]), float(city_info[2]) ax.plot(city_lon, city_lat, 'ro', markersize=4) ax.annotate(city_name, (city_lon, city_lat), fontsize=5) # 绘制地图 if __name__ == '__main__': fig, ax = create_map() draw_boundary(ax, 'boundary.txt') draw_cities(ax, 'cities.txt') plt.show()
代码解释:
- 第2-3行:导入必要的库
- 第5-23行:创建地图
- 第25-33行:绘制国界线
- 第35-44行:绘制城市
- 第47-54行:绘制地图
使用此代码可绘制出包含国界线和城市的平面地图。