如何根据Plotly美国航班地图中的航空公司更改颜色示例



在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' )

如果您查看此处提供的航线的源数据,您会注意到这些数据实际上也提供了航空公司。

我的问题是——根据哪家航空公司提供的航班,改变线路颜色的最简单方法是什么?例如,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()),
)
)

最新更新