如何在美国密谋飞行地图示例中基于航空公司更改颜色

时间:2018-11-16 21:37:54

标签: python python-3.x plotly plotly-dash

在plotly的样本库中,他们提供以下代码来创建显示给定月份美国航班状态的地图:

import plotly.plotly as py
import pandas as pd

df_airports = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_us_airport_traffic.csv')
df_airports.head()

df_flight_paths = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_aa_flight_paths.csv')
df_flight_paths.head()

airports = [ dict(
    type = 'scattergeo',
    locationmode = 'USA-states',
    lon = df_airports['long'],
    lat = df_airports['lat'],
    hoverinfo = 'text',
    text = df_airports['airport'],
    mode = 'markers',
    marker = dict( 
        size=2, 
        color='rgb(255, 0, 0)',
        line = dict(
            width=3,
            color='rgba(68, 68, 68, 0)'
        )
    ))]

flight_paths = []
for i in range( len( df_flight_paths ) ):
flight_paths.append(
    dict(
        type = 'scattergeo',
        locationmode = 'USA-states',
        lon = [ df_flight_paths['start_lon'][i], df_flight_paths['end_lon'][i] ],
        lat = [ df_flight_paths['start_lat'][i], df_flight_paths['end_lat'][i] ],
        mode = 'lines',
        line = dict(
            width = 1,
            color = 'red',
        ),
        opacity = float(df_flight_paths['cnt'][i])/float(df_flight_paths['cnt'].max()),
    )
)

layout = dict(
    title = 'Feb. 2011 American Airline flight paths<br>(Hover for airport names)',
    showlegend = False, 
    geo = dict(
        scope='north america',
        projection=dict( type='azimuthal equal area' ),
        showland = True,
        landcolor = 'rgb(243, 243, 243)',
        countrycolor = 'rgb(204, 204, 204)',
    ),
)

fig = dict( data=flight_paths + airports, layout=layout )
py.iplot( fig, filename='d3-flight-paths' )

如果您查看here提供的航班路线的源数据,您会发现该数据实际上也为航空公司提供了

我的问题是-根据哪家航空公司提供航班更改航线颜色的最简单方法是什么?例如,AA是红色,而Delta是蓝色。

1 个答案:

答案 0 :(得分:0)

进一步检查之后,由于每行都是循环迭代地添加的,因此这很容易解决。通过仅添加一个if / else语句并将颜色分配给一个变量,如下所示,我能够实现所需的结果:

for i in range( len( my_df ) ):
    if my_df['Current Location?'][i] == 'Yes':
        flight_color = 'blue'
    else:
        flight_color = 'red'
    flight_paths.append(
        dict(
            type = 'scattergeo',
            locationmode = 'country names',
            lon = [ my_df['Longitude'][i], -98.5795],
            lat = [ my_df['Latitude'][i], 39.8283],
            mode = 'lines',
            line = dict(
                width = 2,
                color = flight_color,
            ),
            opacity = float(my_df['Passengers'][i])/float(my_df['Passengers'].max()),
        )
    )