如何在 Plotly US Flight Maps 示例中根据航空公司更改颜色

How to Change Colors based on Airline in Plotly US Flight Maps Example

在 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是蓝色的

经过进一步审查,因为每一行都是在循环中迭代添加的,所以修复起来非常简单。只需添加 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()),
        )
    )