使用cartopy画飞机的航线

使用cartopy画飞机的航线

导入cartopy这个工具,它不是一个包,是很多的包的集合,再导入的时候,最好是使用anaconda这个工具导入,这样就方便多了
还要可以使用管理者身份导:conda insatll cartopy

# -*- coding:utf-8 -*-
'''
@author: leishen
@time: 2021/5/29 20:36
'''
import pandas as pd
import numpy as np  # 矩阵类型
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import time

# 设置字体为SimHei显示中文,设置正常显示字符
plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False

city_lon_lati_dicts = {}         #城市坐标
plane_static = {}                #飞机飞行次数
airport_city_dicts = {}          #机场城市对应
city = []                        #飞行记录化成城市
result = []                      #记录飞行城市的坐标

def load_city_lon_lati():
    sheet_names = ['Table ' + str(x) for x in range(1,77)]
    # print(sheet_names)
    for st_name in sheet_names:
        data = pd.read_excel('C:\\Users\\悲陌\\Desktop\\数据可视化\\全国城市经纬度汇总.xlsx',
                             sheet_name = st_name,names=[0,1,2,3,4])
        data = data.iloc[:,1:5]
        # print(data)
        for dt in data.iterrows():

            if(dt[1][1] == dt[1][2]):
                city = dt[1][2]
                lon = dt[1][3]
                lati = dt[1][4]
                city_lon_lati_dicts[city] = (lon,lati)
                # print((city_lon_lati_dicts))
    # print(city_lon_lati_dicts)
    return city_lon_lati_dicts

#航班的动态数据
def load_plane_data():
    data = pd.read_csv('C:\\Users\\悲陌\\Desktop\\数据可视化\\航班动态算法大赛原始数据\\训练集\\'
                       '2015年5月到2017年5月航班动态数据.csv',encoding='gbk',engine="python")
#     选取
    data_normal = data[data['航班是否取消']=='正常']
    nrows, ncols = data_normal.shape
    data_normal.apply(lambda data:handle(data),axis = 1 )
    #dat:出发机场  到达机场  航班编号
    dat = data_normal.iloc[:,:3]

def handle(data):
    start_city = ""
    go_city = ""
    try:
        start_city = airport_city_dicts[data['出发机场']]
        go_city = airport_city_dicts[data['到达机场']]

    except Exception as e:
        pass
    if start_city == "":
        return
    key1 = start_city + "-" + go_city
    if key1 in plane_static:
        plane_static[key1] = plane_static[key1] + 1
    else:
        plane_static[key1] = 1
    # print(plane_static)

def ctiys_airport_code():
    for key in plane_static:
        city.append(key.split("-"))
    for i in range(len(city)):
            for key in city_lon_lati_dicts:
                if city[i][0] in key:
                    result.append(city_lon_lati_dicts[key])
                if city[i][1] in key:
                    result.append(city_lon_lati_dicts[key])
    # print(result)

# 加载机场编号对应城市数据
def load_airport_citys():
    data = pd.read_excel('C:\\Users\\悲陌\\Desktop\\数据可视化\\航班动态算法大赛原始数据\\训练集\\机场城市对应表.xlsx')
    # 遍历data
    #2、加速遍历dataframe
    for data in data.iterrows():
        airport_code = data[1]['机场编码']
        city = data[1]['城市名称'] + '市'
        airport_city_dicts[airport_code] = city
        # print(airport_city_dicts)

def make_china_map():
    # 读取CN-border-La.dat文件
    with open('C:\\Users\\悲陌\\Desktop\\数据可视化\\CN-border-La.dat') as src:
        context = src.read()  # 整个文档都被读进来了,作为str赋值给context
        blocks = [cnt for cnt in context.split('>') if len(cnt) > 0]
        borders = [np.fromstring(block, dtype=float, sep=' ') for block in blocks]
    #     [1 2 3 4,5 6 7 8,]
    # 设置画图各种参数
    fig = plt.figure(figsize=[8, 8])  # 申请一个画布,宽8*高8 inch 英寸 1inch 约等于2.54cm
    # 设置投影类型和经纬度
    ax = plt.axes(projection=ccrs.LambertConformal(central_latitude=90,
                                                   central_longitude=105))
    # 画海,陆地,河流,湖泊
    ax.add_feature(cfeature.OCEAN.with_scale('50m'))
    ax.add_feature(cfeature.LAND.with_scale('50m'))
    ax.add_feature(cfeature.RIVERS.with_scale('50m'))
    ax.add_feature(cfeature.LAKES.with_scale('50m'))
    # 画国界
    for line in borders:
        ax.plot(line[0::2], line[1::2], '-', color='gray', transform=ccrs.Geodetic())
    # 画经纬度网格
    ax.gridlines(linestyle='--')
    # 框出区域
    ax.set_extent([80, 130, 13, 55])
    # 画南海,这一步是新建一个ax,设置投影
    sub_ax = fig.add_axes([0.741, 0.11, 0.14, 0.155],
                          projection=ccrs.LambertConformal(central_latitude=90,
                                                           central_longitude=115))
    # 画海,陆地,河流,湖泊
    sub_ax.add_feature(cfeature.OCEAN.with_scale('50m'))
    sub_ax.add_feature(cfeature.LAND.with_scale('50m'))
    sub_ax.add_feature(cfeature.RIVERS.with_scale('50m'))
    sub_ax.add_feature(cfeature.LAKES.with_scale('50m'))

    # 画边界
    for line in borders:
        sub_ax.plot(line[0::2], line[1::2], '-', color='gray',
                    transform=ccrs.Geodetic())  #
    # 框区域
    sub_ax.set_extent([105, 125, 0, 25])
    provinces = city_lon_lati_dicts

    # 添加省会标记
    colors1 = '#00CED1'
    area = np.pi * 4 ** 2
    for pro in provinces.items():
        ax.scatter(pro[1][0],pro[1][1],s= area , c=colors1,transform=ccrs.Geodetic())

    # 画城市之间的航班线
    tmp_1 = [i[0] for i in result]  # 取了坐标列表的第一列
    tmp_2 = [i[1] for i in result]  # 取了坐标列表的第二列
    for i in range(len(result) - 1):
        ax.plot([tmp_1[i], tmp_1[i + 1]], [tmp_2[i], tmp_2[i + 1]],alpha = 0.2 ,transform=ccrs.Geodetic())
    return ax

if __name__ == '__main__':
    start_time = time.time()
    load_plane_data
    load_airport_citys()
    load_city_lon_lati()
    load_plane_data()
    ctiys_airport_code()
    ax = make_china_map()
    end_time = time.time()
    print("运行时间:".format(),end_time - start_time)
    plt.show()

运行结果:
中国航线图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

一个胖小白

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值