Bootstrap

基于pyecharts的航班数据可视化(附动态航线图)

不多说,直接上代码!
我是在jupyter lab上运动的代码,需要提前输入一下代码才能显示:

# notebook显示图
from pyecharts.globals import CurrentConfig, NotebookType
CurrentConfig.NOTEBOOK_TYPE = NotebookType.JUPYTER_LAB
CurrentConfig.ONLINE_HOST

在这里插入图片描述

数据集链接:https://pan.baidu.com/s/1zSg88vimDHuUKh7BKeHchA?pwd=1111
提取码:1111

机场航班分布图(3D)

import pandas as pd
from pyecharts.charts import Map3D
from pyecharts.globals import ChartType
from pyecharts import options as opts

df0 = pd.read_excel('data/航班数据.xls')
sizes = df0["departure_city"].value_counts()
df1 = pd.DataFrame({'flights_amount': sizes})

df2 = df0[['departure_city', 'departure_cy', 'departure_cx']].drop_duplicates()
df2.index = df2['departure_city']
df2['flights_amount'] = df1

city_lines = list(zip(df2['departure_city'], list(zip(df2['departure_cx'], df2['departure_cy'], df2['flights_amount']))))

c = (
    Map3D()
    .add_schema(
        itemstyle_opts=opts.ItemStyleOpts(
            color="rgb(5,101,123)",
            opacity=1,
            border_width=0.8,
            border_color="rgb(62,215,213)",
        ),
        map3d_label=opts.Map3DLabelOpts(is_show=False),
        emphasis_label_opts=opts.LabelOpts(
            is_show=False,
            color="#fff",
            font_size=10,
            background_color="rgba(0,23,11,0)",
        ),
        light_opts=opts.Map3DLightOpts(
            main_color="#fff",
            main_intensity=1.2,
            main_shadow_quality="high",
            is_main_shadow=False,
            main_beta=10,
            ambient_intensity=0.3,
        ),
    )
    .add(
        series_name="机场所在城市分布图",
        data_pair=city_lines,
        type_=ChartType.BAR3D,
        bar_size=1,
        shading="lambert",
        label_opts=opts.LabelOpts(is_show=False),
    )
    .set_global_opts(
        visualmap_opts=opts.VisualMapOpts(
            is_piecewise=True,
            pieces=[
                {"min": 800, "label": '>800', "color": 'blue'},
                {"min": 500, "max": 799, "label": '500-799', "color": 'red'},
                {"min": 200, "max": 499, "label": '200-499', "color": 'peru'},
                {"min": 100, "max": 199, "label": '100-199', "color": 'orange'},
                {"min": 10, "max": 99, "label": '10-99', "color": 'gold'},
                {"min": 0, "max": 9, "label": '0-9', "color": 'cornsilk'}
            ]
        )
    )
)

c.load_javascript()
c.render_notebook()

在这里插入图片描述

航班桑基图

import pandas as pd
from pyecharts.charts import Sankey
from pyecharts import options as opts
from matplotlib.font_manager import FontProperties

# 数据处理
df0 = pd.read_excel('data/航班数据.xls')#读取数据
df1 = df0[df0.departure_airport.isin(df0.departure_airport.values)]  
df2 = df1.groupby(by=['departure_airport','landing_airport']).size().reset_index()  # 汇总各航班的目的地数
df2.rename(columns={'departure_airport':'source','landing_airport':'target',0:'value'}, inplace=True)
df3 = df2.query('value>=5').copy()  # 选择目的地数目超过5的航班
df4 = df3
df4.drop_duplicates(subset='target', keep='first', inplace=True)
df4 = pd.concat([df4,df3[df3.target.isin(df.departure_airport.values)].drop_duplicates(subset='target',keep='first')])
df4.drop_duplicates(subset='target', keep=False, inplace=True)


# 生成nodes
df = df0.groupby(by='departure_airport').agg({'departure_city':'count'}).reset_index().sort_values(by='departure_city', ascending=False).query('departure_city>500')
nodes = []
for i in df['departure_airport']:
    dic = {}
    dic['name'] = i
    nodes.append(dic)
for i in df4['target']:
    dic = {}
    dic['name'] = i
    nodes.append(dic)
    
#生成links
links = []
for i in df3.drop(index=df3[df3['target'].isin(df['departure_airport'].values)].index).values:
    dic = {}
    dic['source'] = i[0]
    dic['target'] = i[1]
    dic['value'] = i[2]
    links.append(dic)
    
# 生成桑基图
c = (
    Sankey(init_opts=opts.InitOpts(width="900px", height="1200px"))
    .add(
        series_name="航班量超过500的机场出发(目的地>5)",
        nodes=nodes,
        links=links,
        linestyle_opt=opts.LineStyleOpts(opacity=0.2, curve=0.1, color="source"),
        label_opts=opts.LabelOpts(position="right"),
    )
)
c.load_javascript()
c.render_notebook()

在这里插入图片描述

航线关系图

from pyecharts import options as opts
from pyecharts.charts import Graph
import pandas as pd
import pandas as pd

# 读取和预处理数据
df0 = pd.read_excel('data/航班数据.xls')
df1 = df0["departure_city"].value_counts() 
df1 = pd.DataFrame({'name': df1.index, "symbolSize": df1.values})

# 生成节点数据
nodes = []
for i in df1.values:
    dic1 = {}
    dic1['name'] = i[0]
    dic1['symbolSize'] = i[1] / 50  # 调整节点大小
    dic1['value'] = i[1]
    nodes.append(dic1)

# 生成连线数据
df2 = df0[['departure_city', 'landing_city']].drop_duplicates()
links = []
for j in df2.values:
    dic2 = {}
    dic2['source'] = j[0]
    dic2['target'] = j[1]
    links.append(dic2)

# 创建关系图
c = (
    Graph(init_opts=opts.InitOpts(width="1200px", height="900px"))
    .set_colors('blue') 
    .add(
        "",
        nodes, 
        links, 
        layout="circular",  # 设置布局为圆形
        is_rotate_label=True,  # 旋转标签以提高可见性
        linestyle_opts=opts.LineStyleOpts(opacity=0.4, curve=0.3, color="source", width=0.5),  # 线条样式选项
        label_opts=opts.LabelOpts(position='center', font_size=8),  # 标签选项
    )
    .set_global_opts(title_opts=opts.TitleOpts(title="出发航线关系图"))  # 设置标题
)

c.load_javascript()
c.render_notebook()

在这里插入图片描述

动态航线图

import pandas as pd
import numpy as np
from pyecharts import options as opts
from pyecharts.charts import Geo
from pyecharts.globals import ChartType, SymbolType

# 获取数据及预处理
df = pd.read_excel('data/航班数据.xls')
df1 = df[['departure_city','departure_airport','departure_y','departure_x','landing_city','landing_airport','landing_y','landing_x']].copy()
df2 = df1[['departure_city','departure_airport','departure_y','departure_x']].copy()
df2.rename(columns={'departure_city':'city','departure_airport':'airport','departure_y':'lat','departure_x':'lon'}, inplace=True)
df3 = df1[['landing_city','landing_airport','landing_y','landing_x']].copy()
df3.rename(columns={'landing_city':'city','landing_airport':'airport','landing_y':'lat','landing_x':'lon'}, inplace=True)
df2 = pd.concat([df2,df3])
df2.drop_duplicates(subset='airport', keep='first', inplace=True)
airportPoint = list(zip(df2['airport'],list(zip(round(df2['lon'],2),round(df2['lat'],2)))))
airportData = list(zip(df2['airport'],df2['city']))


# 航线起始
df_by = df1[df1.departure_airport=='白云机场'].copy()
by_data = list(zip(df_by.drop_duplicates(subset='landing_airport',keep='first')['departure_airport'],df_by.drop_duplicates(subset='landing_airport',keep='first')['landing_airport']))
df_jb = df1[df1.departure_airport=='江北机场'].copy()
jb_data = list(zip(df_jb.drop_duplicates(subset='landing_airport',keep='first')['departure_airport'],df_jb.drop_duplicates(subset='landing_airport',keep='first')['landing_airport']))
df_ba = df1[df1.departure_airport=='宝安机场'].copy()
ba_data = list(zip(df_ba.drop_duplicates(subset='landing_airport',keep='first')['departure_airport'],df_ba.drop_duplicates(subset='landing_airport',keep='first')['landing_airport']))
df_cs = df1[df1.departure_airport=='长水机场'].copy()
cs_data = list(zip(df_cs.drop_duplicates(subset='landing_airport',keep='first')['departure_airport'],df_cs.drop_duplicates(subset='landing_airport',keep='first')['landing_airport']))
df_xs = df1[df1.departure_airport=='萧山机场'].copy()
xs_data = list(zip(df_xs.drop_duplicates(subset='landing_airport',keep='first')['departure_airport'],df_xs.drop_duplicates(subset='landing_airport',keep='first')['landing_airport']))
df_sl = df1[df1.departure_airport=='双流机场'].copy()
sl_data = list(zip(df_sl.drop_duplicates(subset='landing_airport',keep='first')['departure_airport'],df_sl.drop_duplicates(subset='landing_airport',keep='first')['landing_airport']))
df_hq = df1[df1.departure_airport=='虹桥机场'].copy()
hq_data = list(zip(df_hq.drop_duplicates(subset='landing_airport',keep='first')['departure_airport'],df_hq.drop_duplicates(subset='landing_airport',keep='first')['landing_airport']))
df_pd = df1[df1.departure_airport=='浦东机场'].copy()
pd_data = list(zip(df_pd.drop_duplicates(subset='landing_airport',keep='first')['departure_airport'],df_pd.drop_duplicates(subset='landing_airport',keep='first')['landing_airport']))
df_xy = df1[df1.departure_airport=='咸阳机场'].copy()
xy_data = list(zip(df_xy.drop_duplicates(subset='landing_airport',keep='first')['departure_airport'],df_xy.drop_duplicates(subset='landing_airport',keep='first')['landing_airport']))

# 飞机形状
plane = 'path://M1705.06,1318.313v-89.254l-319.9-221.799l0.073-208.063c0.521-84.662-26.629-121.796-63.961-121.491c-37.332-0.305-64.482,36.829-63.961,121.491l0.073,208.063l-319.9,221.799v89.254l330.343-157.288l12.238,241.308l-134.449,92.931l0.531,42.034l175.125-42.917l175.125,42.917l0.531-42.034l-134.449-92.931l12.238-241.308L1705.06,1318.313z'

# 创建地理坐标系图对象
geo = (
      Geo(init_opts=opts.InitOpts(width="1200px", height="1200px"))
      .add_schema(
          maptype="china",
          itemstyle_opts=opts.ItemStyleOpts(color="#000000", border_color="#1E90FF"),
          emphasis_label_opts=opts.LabelOpts(is_show=False),
          emphasis_itemstyle_opts=opts.ItemStyleOpts(color='#323c48'),
    )
)

# 添加机场坐标
for airport, coordinate in airportPoint:
    geo.add_coordinate(airport, *coordinate)
    
# 添加机场分布数据
geo.add(
    series_name="机场分布",
    data_pair=airportData,
    symbol_size=6,
    color="#E1FFFF",
).set_series_opts(
    label_opts=opts.LabelOpts(is_show=False),
).set_global_opts(
    title_opts=opts.TitleOpts(title="")
)

# 航线
geo.add(
    "白云机场航线",
    by_data,
    type_=ChartType.LINES,
    symbol_size=2,
    effect_opts=opts.EffectOpts(
        symbol=plane,
        symbol_size=7,
        trail_length=0,
        period=5,
        is_show=True,
        color="white"
    ),
    linestyle_opts=opts.LineStyleOpts(
        # type_='dashed',
        width=0.3,
        curve=0.2,
        color='#1E90FF',),
)
geo.add(
    "江北机场航线",
    jb_data,
    type_=ChartType.LINES,
    symbol_size=2,
    effect_opts=opts.EffectOpts(
        symbol=plane,
        symbol_size=7,
        trail_length=0,
        period=5,
        is_show=True,
        color="white"
    ),
    linestyle_opts=opts.LineStyleOpts(
        # type_='dashed',
        width=0.3,
        curve=0.2,
        color='#1E90FF',),
)
geo.add(
    "保安机场航线",
    ba_data,
    type_=ChartType.LINES,
    symbol_size=2,
    effect_opts=opts.EffectOpts(
        symbol=plane,
        symbol_size=7,
        trail_length=0,
        period=5,
        is_show=True,
        color="white"
    ),
    linestyle_opts=opts.LineStyleOpts(
        # type_='dashed',
        width=0.3,
        curve=0.2,
        color='#1E90FF',),
)
geo.add(
    "长水机场航线",
    cs_data,
    type_=ChartType.LINES,
    symbol_size=2,
    effect_opts=opts.EffectOpts(
        symbol=plane,
        symbol_size=7,
        trail_length=0,
        period=5,
        is_show=True,
        color="white"
    ),
    linestyle_opts=opts.LineStyleOpts(
        # type_='dashed',
        width=0.3,
        curve=0.2,
        color='#1E90FF',),
)
geo.add(
    "萧山机场航线",
    xs_data,
    type_=ChartType.LINES,
    symbol_size=2,
    effect_opts=opts.EffectOpts(
        symbol=plane,
        symbol_size=7,
        trail_length=0,
        period=5,
        is_show=True,
        color="white"
    ),
    linestyle_opts=opts.LineStyleOpts(
        # type_='dashed',
        width=0.3,
        curve=0.2,
        color='#1E90FF',),
)
geo.add(
    "双流机场航线",
    sl_data,
    type_=ChartType.LINES,
    symbol_size=2,
    effect_opts=opts.EffectOpts(
        symbol=plane,
        symbol_size=7,
        trail_length=0,
        period=5,
        is_show=True,
        color="white"
    ),
    linestyle_opts=opts.LineStyleOpts(
        # type_='dashed',
        width=0.3,
        curve=0.2,
        color='#1E90FF',),
)
geo.add(
    "虹桥机场航线",
    hq_data,
    type_=ChartType.LINES,
    symbol_size=2,
    effect_opts=opts.EffectOpts(
        symbol=plane,
        symbol_size=7,
        trail_length=0,
        period=5,
        is_show=True,
        color="white"
    ),
    linestyle_opts=opts.LineStyleOpts(
        # type_='dashed',
        width=0.3,
        curve=0.2,
        color='#1E90FF',),
)
geo.add(
    "浦东机场航线",
    pd_data,
    type_='lines',
    symbol_size=2,
    is_large=True,
    effect_opts=opts.EffectOpts(
        symbol=plane,
        symbol_size=7,
        trail_length=0,
        period=5,
        is_show=True,
        color="white",
    ),
    linestyle_opts=opts.LineStyleOpts(
        # type_='dashed',
        width=0.3,
        curve=0.2,
        color='#1E90FF',),
)
geo.add(
    "咸阳机场航线",
    xy_data,
    type_=ChartType.LINES,
    symbol_size=2,
    effect_opts=opts.EffectOpts(
        symbol=plane,
        symbol_size=7,
        trail_length=0,
        period=5,
        is_show=True,
        color="white"
    ),
    linestyle_opts=opts.LineStyleOpts(
        # type_='dashed',
        width=0.3,
        curve=0.2,
        color='#1E90FF',),
)

# 标签
geo.set_series_opts(label_opts=opts.LabelOpts(is_show=False))

# 图例
geo.set_global_opts(
        title_opts=opts.TitleOpts(title="国内航线图", pos_top='3%', pos_left='center'),
        tooltip_opts=opts.TooltipOpts(is_show=True),
        legend_opts=opts.LegendOpts(is_show=True, pos_left='left', pos_top='50%', orient='vertical',
                                    selected_mode='single')
)

geo.load_javascript()
geo.render_notebook()

在这里插入图片描述

;