自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

7款Python數(shù)據(jù)圖表工具的比較

大數(shù)據(jù) 數(shù)據(jù)可視化
本文會(huì)基于一份真實(shí)的數(shù)據(jù),使用這些庫(kù)來對(duì)數(shù)據(jù)進(jìn)行可視化。通過這些對(duì)比,我們期望了解每個(gè)庫(kù)所適用的范圍,以及如何更好的利用整個(gè) Python 的數(shù)據(jù)可視化的生態(tài)系統(tǒng)。

[[200381]]

Python 的科學(xué)棧相當(dāng)成熟,各種應(yīng)用場(chǎng)景都有相關(guān)的模塊,包括機(jī)器學(xué)習(xí)和數(shù)據(jù)分析。數(shù)據(jù)可視化是發(fā)現(xiàn)數(shù)據(jù)和展示結(jié)果的重要一環(huán),只不過過去以來,相對(duì)于 R 這樣的工具,發(fā)展還是落后一些。

幸運(yùn)的是,過去幾年出現(xiàn)了很多新的Python數(shù)據(jù)可視化庫(kù),彌補(bǔ)了一些這方面的差距。matplotlib 已經(jīng)成為事實(shí)上的數(shù)據(jù)可視化方面最主要的庫(kù),此外還有很多其他庫(kù),例如vispy,bokeh, seaborn, pyga, folium 和 networkx,這些庫(kù)有些是構(gòu)建在 matplotlib 之上,還有些有其他一些功能。

本文會(huì)基于一份真實(shí)的數(shù)據(jù),使用這些庫(kù)來對(duì)數(shù)據(jù)進(jìn)行可視化。通過這些對(duì)比,我們期望了解每個(gè)庫(kù)所適用的范圍,以及如何更好的利用整個(gè) Python 的數(shù)據(jù)可視化的生態(tài)系統(tǒng)。

我們?cè)?Dataquest 建了一個(gè)交互課程,教你如何使用 Python 的數(shù)據(jù)可視化工具。如果你打算深入學(xué)習(xí),可以點(diǎn)這里。

探索數(shù)據(jù)集

在我們探討數(shù)據(jù)的可視化之前,讓我們先來快速的瀏覽一下我們將要處理的數(shù)據(jù)集。我們將要使用的數(shù)據(jù)來自 openflights。我們將要使用航線數(shù)據(jù)集、機(jī)場(chǎng)數(shù)據(jù)集、航空公司數(shù)據(jù)集。其中,路徑數(shù)據(jù)的每一行對(duì)應(yīng)的是兩個(gè)機(jī)場(chǎng)之間的飛行路徑;機(jī)場(chǎng)數(shù)據(jù)的每一行對(duì)應(yīng)的是世界上的某一個(gè)機(jī)場(chǎng),并且給出了相關(guān)信息;航空公司的數(shù)據(jù)的每一行給出的是每一個(gè)航空公司。

首先我們先讀取數(shù)據(jù):

  1. # Import the pandas library. 
  2. import pandas 
  3. Read in the airports data. 
  4. airports = pandas.read_csv("airports.csv", header=None, dtype=str) 
  5. airports.columns = ["id""name""city""country""code""icao""latitude""longitude""altitude""offset""dst""timezone"
  6. Read in the airlines data. 
  7. airlines = pandas.read_csv("airlines.csv", header=None, dtype=str) 
  8. airlines.columns = ["id""name""alias""iata""icao""callsign""country""active"
  9. Read in the routes data. 
  10. routes = pandas.read_csv("routes.csv", header=None, dtype=str) 
  11. routes.columns = ["airline""airline_id""source""source_id""dest""dest_id""codeshare""stops""equipment" 

這些數(shù)據(jù)沒有列的***項(xiàng),因此我們通過賦值 column 屬性來添加列的***項(xiàng)。我們想要將每一列作為字符串進(jìn)行讀取,因?yàn)檫@樣做可以簡(jiǎn)化后續(xù)以行 id 為匹配,對(duì)不同的數(shù)據(jù)框架進(jìn)行比較的步驟。我們?cè)谧x取數(shù)據(jù)時(shí)設(shè)置了 dtype 屬性值達(dá)到這一目的。

我們可以快速瀏覽一下每一個(gè)數(shù)據(jù)集的數(shù)據(jù)框架。

  1. airports.head() 

 

  1. airlines.head() 

 

  1. routes.head()  

 

我們可以分別對(duì)每一個(gè)單獨(dú)的數(shù)據(jù)集做許多不同有趣的探索,但是只要將它們結(jié)合起來分析才能取得***的收獲。Pandas 將會(huì)幫助我們分析數(shù)據(jù),因?yàn)樗軌蛴行У倪^濾權(quán)值或者通過它來應(yīng)用一些函數(shù)。我們將會(huì)深入幾個(gè)有趣的權(quán)值因子,比如分析航空公司和航線。

那么在此之前我們需要做一些數(shù)據(jù)清洗的工作。

  1. routes = routes[routes["airline_id"] != "\\N"

這一行命令就確保了我們?cè)?airline_id 這一列只含有數(shù)值型數(shù)據(jù)。

制作柱狀圖

現(xiàn)在我們理解了數(shù)據(jù)的結(jié)構(gòu),我們可以進(jìn)一步地開始描點(diǎn)來繼續(xù)探索這個(gè)問題。首先,我們將要使用 matplotlib 這個(gè)工具,matplotlib 是一個(gè)相對(duì)底層的 Python 棧中的描點(diǎn)庫(kù),所以它比其他的工具庫(kù)要多敲一些命令來做出一個(gè)好看的曲線。另外一方面,你可以使用 matplotlib 幾乎做出任何的曲線,這是因?yàn)樗值撵`活,而靈活的代價(jià)就是非常難于使用。

我們首先通過做出一個(gè)柱狀圖來顯示不同的航空公司的航線長(zhǎng)度分布。一個(gè)柱狀圖將所有的航線的長(zhǎng)度分割到不同的值域,然后對(duì)落入到不同的值域范圍內(nèi)的航線進(jìn)行計(jì)數(shù)。從中我們可以知道哪些航空公司的航線長(zhǎng),哪些航空公司的航線短。

為了達(dá)到這一點(diǎn),我們需要首先計(jì)算一下航線的長(zhǎng)度,***步就要使用距離公式,我們將會(huì)使用余弦半正矢距離公式來計(jì)算經(jīng)緯度刻畫的兩個(gè)點(diǎn)之間的距離。

  1. import math 
  2. def haversine(lon1, lat1, lon2, lat2): 
  3.     # Convert coordinates to floats. 
  4.     lon1, lat1, lon2, lat2 = [float(lon1), float(lat1), float(lon2), float(lat2)] 
  5.     # Convert to radians from degrees. 
  6.     lon1, lat1, lon2, lat2 = map(math.radians, [lon1, lat1, lon2, lat2]) 
  7.     # Compute distance. 
  8.     dlon = lon2 - lon1  
  9.     dlat = lat2 - lat1  
  10.     a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2 
  11.     c = 2 * math.asin(math.sqrt(a))  
  12.     km = 6367 * c 
  13.     return km  

然后我們就可以使用一個(gè)函數(shù)來計(jì)算起點(diǎn)機(jī)場(chǎng)和終點(diǎn)機(jī)場(chǎng)之間的單程距離。我們需要從路線數(shù)據(jù)框架得到機(jī)場(chǎng)數(shù)據(jù)框架所對(duì)應(yīng)的 source_id 和 dest_id,然后與機(jī)場(chǎng)的數(shù)據(jù)集的 id 列相匹配,然后就只要計(jì)算就行了,這個(gè)函數(shù)是這樣的:

  1. def calc_dist(row): 
  2.     dist = 0 
  3.     try: 
  4.         # Match source and destination to get coordinates. 
  5.         source = airports[airports["id"] == row["source_id"]].iloc[0] 
  6.         dest = airports[airports["id"] == row["dest_id"]].iloc[0] 
  7.         # Use coordinates to compute distance. 
  8.         dist = haversine(dest["longitude"], dest["latitude"], source["longitude"], source["latitude"]) 
  9.     except (ValueError, IndexError): 
  10.         pass 
  11.     return dist  

如果 source_id 和 dest_id 列沒有有效值的話,那么這個(gè)函數(shù)會(huì)報(bào)錯(cuò)。因此我們需要增加 try/catch 模塊對(duì)這種無效的情況進(jìn)行捕捉。

***,我們將要使用 pandas 來將距離計(jì)算的函數(shù)運(yùn)用到 routes 數(shù)據(jù)框架。這將會(huì)使我們得到包含所有的航線線長(zhǎng)度的 pandas 序列,其中航線線的長(zhǎng)度都是以公里做單位。

  1. route_lengths = routes.apply(calc_dist, axis=1) 

現(xiàn)在我們就有了航線距離的序列了,我們將會(huì)創(chuàng)建一個(gè)柱狀圖,它將會(huì)將數(shù)據(jù)歸類到對(duì)應(yīng)的范圍之內(nèi),然后計(jì)數(shù)分別有多少的航線落入到不同的每個(gè)范圍:

  1. import matplotlib.pyplot as plt  
  2. %matplotlib inline  
  3.  
  4. plt.hist(route_lengths, bins=20)  

 

我們用 import matplotlib.pyplot as plt 導(dǎo)入 matplotlib 描點(diǎn)函數(shù)。然后我們就使用 %matplotlib inline 來設(shè)置 matplotlib 在 ipython 的 notebook 中描點(diǎn),最終我們就利用 plt.hist(route_lengths, bins=20) 得到了一個(gè)柱狀圖。正如我們看到的,航空公司傾向于運(yùn)行近距離的短程航線,而不是遠(yuǎn)距離的遠(yuǎn)程航線。

使用 seaborn

我們可以利用 seaborn 來做類似的描點(diǎn),seaborn 是一個(gè) Python 的高級(jí)庫(kù)。Seaborn 建立在 matplotlib 的基礎(chǔ)之上,做一些類型的描點(diǎn),這些工作常常與簡(jiǎn)單的統(tǒng)計(jì)工作有關(guān)。我們可以基于一個(gè)核心的概率密度的期望,使用 distplot 函數(shù)來描繪一個(gè)柱狀圖。一個(gè)核心的密度期望是一個(gè)曲線 —— 本質(zhì)上是一個(gè)比柱狀圖平滑一點(diǎn)的,更容易看出其中的規(guī)律的曲線。

  1. import seaborn 
  2.  
  3. seaborn.distplot(route_lengths, bins=20) 

 

正如你所看到的那樣,seaborn 同時(shí)有著更加好看的默認(rèn)風(fēng)格。seaborn 不含有與每個(gè) matplotlib 的版本相對(duì)應(yīng)的版本,但是它的確是一個(gè)很好的快速描點(diǎn)工具,而且相比于 matplotlib 的默認(rèn)圖表可以更好的幫助我們理解數(shù)據(jù)背后的含義。如果你想更深入的做一些統(tǒng)計(jì)方面的工作的話,seaborn 也不失為一個(gè)很好的庫(kù)。

條形圖

柱狀圖也雖然很好,但是有時(shí)候我們會(huì)需要航空公司的平均路線長(zhǎng)度。這時(shí)候我們可以使用條形圖--每條航線都會(huì)有一個(gè)單獨(dú)的狀態(tài)條,顯示航空公司航線的平均長(zhǎng)度。從中我們可以看出哪家是國(guó)內(nèi)航空公司哪家是國(guó)際航空公司。我們可以使用pandas,一個(gè)python的數(shù)據(jù)分析庫(kù),來酸楚每個(gè)航空公司的平均航線長(zhǎng)度。

  1. import numpy 
  2. # Put relevant columns into a dataframe. 
  3. route_length_df = pandas.DataFrame({"length": route_lengths, "id": routes["airline_id"]}) 
  4. # Compute the mean route length per airline. 
  5. airline_route_lengths = route_length_df.groupby("id").aggregate(numpy.mean) 
  6. # Sort by length so we can make a better chart. 
  7. airline_route_lengths = airline_route_lengths.sort("length", ascending=False 

我們首先用航線長(zhǎng)度和航空公司的id來搭建一個(gè)新的數(shù)據(jù)框架。我們基于airline_id把route_length_df拆分成組,為每個(gè)航空公司建立一個(gè)大體的數(shù)據(jù)框架。然后我們調(diào)用pandas的aggregate函數(shù)來獲取航空公司數(shù)據(jù)框架中長(zhǎng)度列的均值,然后把每個(gè)獲取到的值重組到一個(gè)新的數(shù)據(jù)模型里。之后把數(shù)據(jù)模型進(jìn)行排序,這樣就使得擁有最多航線的航空公司拍到了前面。

這樣就可以使用matplotlib把結(jié)果畫出來。

  1. plt.bar(range(airline_route_lengths.shape[0]), airline_route_lengths["length"]) 

 

Matplotlib的plt.bar方法根據(jù)每個(gè)數(shù)據(jù)模型的航空公司平均航線長(zhǎng)度(airline_route_lengths[“length”])來做圖。

問題是我們想看出哪家航空公司擁有的航線長(zhǎng)度是什么并不容易。為了解決這個(gè)問題,我們需要能夠看到坐標(biāo)軸標(biāo)簽。這有點(diǎn)難,畢竟有這么多的航空公司。一個(gè)能使問題變得簡(jiǎn)單的方法是使圖表具有交互性,這樣能實(shí)現(xiàn)放大跟縮小來查看軸標(biāo)簽。我們可以使用bokeh庫(kù)來實(shí)現(xiàn)這個(gè)--它能便捷的實(shí)現(xiàn)交互性,作出可縮放的圖表。

要使用booked,我們需要先對(duì)數(shù)據(jù)進(jìn)行預(yù)處理:

  1. def lookup_name(row): 
  2.     try: 
  3.         # Match the row id to the id in the airlines dataframe so we can get the name
  4.         name = airlines["name"][airlines["id"] == row["id"]].iloc[0] 
  5.     except (ValueError, IndexError): 
  6.         name = "" 
  7.     return name 
  8. Add the index (the airline ids) as a column
  9. airline_route_lengths["id"] = airline_route_lengths.index.copy() 
  10. # Find all the airline names. 
  11. airline_route_lengths["name"] = airline_route_lengths.apply(lookup_name, axis=1) 
  12. # Remove duplicate values in the index
  13. airline_route_lengths.index = range(airline_route_lengths.shape[0])  

上面的代碼會(huì)獲取airline_route_lengths中每列的名字,然后添加到name列上,這里存貯著每個(gè)航空公司的名字。我們也添加到id列上以實(shí)現(xiàn)查找(apply函數(shù)不傳index)。

***,我們重置索引序列以得到所有的特殊值。沒有這一步,Bokeh 無法正常運(yùn)行。

現(xiàn)在,我們可以繼續(xù)說圖表問題:

  1. import numpy as np 
  2. from bokeh.io import output_notebook 
  3. from bokeh.charts import Bar, show 
  4. output_notebook() 
  5. p = Bar(airline_route_lengths, 'name'values='length', title="Average airline route lengths"
  6. show(p)  

用 output_notebook 創(chuàng)建背景虛化,在 iPython 的 notebook 里畫出圖。然后,使用數(shù)據(jù)幀和特定序列制作條形圖。***,顯示功能會(huì)顯示出該圖。

這個(gè)圖實(shí)際上不是一個(gè)圖像--它是一個(gè) JavaScript 插件。因此,我們?cè)谙旅嬲故镜氖且环聊唤貓D,而不是真實(shí)的表格。

有了它,我們可以放大,看哪一趟航班的飛行路線最長(zhǎng)。上面的圖像讓這些表格看起來擠在了一起,但放大以后,看起來就方便多了。

水平條形圖

Pygal 是一個(gè)能快速制作出有吸引力表格的數(shù)據(jù)分析庫(kù)。我們可以用它來按長(zhǎng)度分解路由。首先把我們的路由分成短、中、長(zhǎng)三個(gè)距離,并在 route_lengths 里計(jì)算出它們各占的百分比。

  1. long_routes = len([k for k in route_lengths if k > 10000]) / len(route_lengths) 
  2.  
  3. medium_routes = len([k for k in route_lengths if k < 10000 and k > 2000]) / len(route_lengths) 
  4.  
  5. short_routes = len([k for k in route_lengths if k < 2000]) / len(route_lengths)  

然后我們可以在 Pygal 的水平條形圖里把每一個(gè)都繪成條形圖:

  1. import pygal 
  2. from IPython.display import SVG 
  3. chart = pygal.HorizontalBar() 
  4. chart.title = 'Long, medium, and short routes' 
  5. chart.add('Long', long_routes * 100) 
  6. chart.add('Medium', medium_routes * 100) 
  7. chart.add('Short', short_routes * 100) 
  8. chart.render_to_file('routes.svg'
  9. SVG(filename='routes.svg' 

 

首先,我們創(chuàng)建一個(gè)空?qǐng)D。然后,我們添加元素,包括標(biāo)題和條形圖。每個(gè)條形圖通過百分比值(***值是100)顯示出該類路由的使用頻率。

***,我們把圖表渲染成文件,用 IPython 的 SVG 功能載入并展示文件。這個(gè)圖看上去比默認(rèn)的 matplotlib 圖好多了。但是為了制作出這個(gè)圖,我們要寫的代碼也多很多。因此,Pygal 可能比較適用于制作小型的展示用圖表。

散點(diǎn)圖

在散點(diǎn)圖里,我們能夠縱向比較數(shù)據(jù)。我們可以做一個(gè)簡(jiǎn)單的散點(diǎn)圖來比較航空公司的 id 號(hào)和航空公司名稱的長(zhǎng)度:

  1. name_lengths = airlines["name"].apply(lambda x: len(str(x))) 
  2.  
  3. plt.scatter(airlines["id"].astype(int), name_lengths) 

 

首先,我們使用 pandasapplymethod 計(jì)算每個(gè)名稱的長(zhǎng)度。它將找到每個(gè)航空公司的名字字符的數(shù)量。然后,我們使用 matplotlib 做一個(gè)散點(diǎn)圖來比較航空 id 的長(zhǎng)度。當(dāng)我們繪制時(shí),我們把 theidcolumn of airlines 轉(zhuǎn)換為整數(shù)類型。如果我們不這樣做是行不通的,因?yàn)樗枰?x 軸上的數(shù)值。我們可以看到不少的長(zhǎng)名字都出現(xiàn)在早先的 id 中。這可能意味著航空公司在成立前往往有較長(zhǎng)的名字。

我們可以使用 seaborn 驗(yàn)證這個(gè)直覺。Seaborn 增強(qiáng)版的散點(diǎn)圖,一個(gè)聯(lián)合的點(diǎn),它顯示了兩個(gè)變量是相關(guān)的,并有著類似地分布。

  1. data = pandas.DataFrame({"lengths": name_lengths, "ids": airlines["id"].astype(int)}) 
  2.  
  3. seaborn.jointplot(x="ids", y="lengths", data=data) 

 

上面的圖表明,兩個(gè)變量之間的相關(guān)性是不明確的——r 的平方值是低的。

靜態(tài) maps

我們的數(shù)據(jù)天然的適合繪圖-機(jī)場(chǎng)有經(jīng)度和緯度對(duì),對(duì)于出發(fā)和目的機(jī)場(chǎng)來說也是。

***張圖做的是顯示全世界的所有機(jī)場(chǎng)??梢杂脭U(kuò)展于 matplotlib 的 basemap 來做這個(gè)。這允許畫世界地圖和添加點(diǎn),而且很容易定制。

  1. # Import the basemap package 
  2. from mpl_toolkits.basemap import Basemap 
  3. Create a map on which to draw.  We're using a mercator projection, and showing the whole world. 
  4. m = Basemap(projection='merc',llcrnrlat=-80,urcrnrlat=80,llcrnrlon=-180,urcrnrlon=180,lat_ts=20,resolution='c'
  5. # Draw coastlines, and the edges of the map. 
  6. m.drawcoastlines() 
  7. m.drawmapboundary() 
  8. Convert latitude and longitude to x and y coordinates 
  9. x, y = m(list(airports["longitude"].astype(float)), list(airports["latitude"].astype(float))) 
  10. # Use matplotlib to draw the points onto the map. 
  11. m.scatter(x,y,1,marker='o',color='red'
  12. # Show the plot. 
  13. plt.show()  

在上面的代碼中,首先用 mercator projection 畫一個(gè)世界地圖。墨卡托投影是將整個(gè)世界的繪圖投射到二位曲面。然后,在地圖上用紅點(diǎn)點(diǎn)畫機(jī)場(chǎng)。

上面地圖的問題是找到每個(gè)機(jī)場(chǎng)在哪是困難的-他們就是在機(jī)場(chǎng)密度高的區(qū)域合并城一團(tuán)紅色斑點(diǎn)。

就像聚焦不清楚,有個(gè)交互制圖的庫(kù),folium,可以進(jìn)行放大地圖來幫助我們找到個(gè)別的機(jī)場(chǎng)。

  1. import folium 
  2. # Get a basic world map. 
  3. airports_map = folium.Map(location=[30, 0], zoom_start=2) 
  4. # Draw markers on the map. 
  5. for name, row in airports.iterrows(): 
  6.     # For some reason, this one airport causes issues with the map. 
  7.     if row["name"] != "South Pole Station"
  8.         airports_map.circle_marker(location=[row["latitude"], row["longitude"]], popup=row["name"]) 
  9. Create and show the map. 
  10. airports_map.create_map('airports.html'
  11. airports_map  

Folium 使用 leaflet.js 來制作全交互式地圖。你可以點(diǎn)擊每一個(gè)機(jī)場(chǎng)在彈出框中看名字。在上邊顯示一個(gè)截屏,但是實(shí)際的地圖更令人印象深刻。Folium 也允許非常廣闊的修改選項(xiàng)來做更好的標(biāo)注,或者添加更多的東西到地圖上。

畫弧線

在地圖上看到所有的航空路線是很酷的,幸運(yùn)的是,我們可以使用 basemap 來做這件事。我們將畫弧線連接所有的機(jī)場(chǎng)出發(fā)地和目的地。每個(gè)弧線想展示一個(gè)段都航線的路徑。不幸的是,展示所有的線路又有太多的路由,這將會(huì)是一團(tuán)糟。替代,我們只現(xiàn)實(shí)前 3000 個(gè)路由。

  1. # Make a base map with a mercator projection.  Draw the coastlines. 
  2. m = Basemap(projection='merc',llcrnrlat=-80,urcrnrlat=80,llcrnrlon=-180,urcrnrlon=180,lat_ts=20,resolution='c'
  3. m.drawcoastlines() 
  4. # Iterate through the first 3000 rows
  5. for name, row in routes[:3000].iterrows(): 
  6.     try: 
  7.         # Get the source and dest airports. 
  8.         source = airports[airports["id"] == row["source_id"]].iloc[0] 
  9.         dest = airports[airports["id"] == row["dest_id"]].iloc[0] 
  10.         # Don't draw overly long routes. 
  11.         if abs(float(source["longitude"]) - float(dest["longitude"])) < 90: 
  12.             # Draw a great circle between source and dest airports. 
  13.             m.drawgreatcircle(float(source["longitude"]), float(source["latitude"]), float(dest["longitude"]), float(dest["latitude"]),linewidth=1,color='b'
  14.     except (ValueError, IndexError): 
  15.         pass 
  16.      
  17. # Show the map. 
  18. plt.show()  

 

上面的代碼將會(huì)畫一個(gè)地圖,然后再在地圖上畫線路。我們添加一了寫過濾器來阻止過長(zhǎng)的干擾其他路由的長(zhǎng)路由。

畫網(wǎng)絡(luò)圖

我們將做的最終的探索是畫一個(gè)機(jī)場(chǎng)網(wǎng)絡(luò)圖。每個(gè)機(jī)場(chǎng)將會(huì)是網(wǎng)絡(luò)中的一個(gè)節(jié)點(diǎn),并且如果兩點(diǎn)之間有路由將劃出節(jié)點(diǎn)之間的連線。如果有多重路由,將添加線的權(quán)重,以顯示機(jī)場(chǎng)連接的更多。將使用 networkx 庫(kù)來做這個(gè)功能。

首先,計(jì)算機(jī)場(chǎng)之間連線的權(quán)重。

  1. # Initialize the weights dictionary. 
  2. weights = {} 
  3. # Keep track of keys that have been added once -- we only want edges with a weight of more than 1 to keep our network size manageable. 
  4. added_keys = [] 
  5. # Iterate through each route. 
  6. for name, row in routes.iterrows(): 
  7.     # Extract the source and dest airport ids. 
  8.     source = row["source_id"
  9.     dest = row["dest_id"
  10.      
  11.     # Create a key for the weights dictionary. 
  12.     # This corresponds to one edge, and has the start and end of the route. 
  13.     key = "{0}_{1}".format(source, dest) 
  14.     # If the key is already in weights, increment the weight. 
  15.     if key in weights: 
  16.         weights[key] += 1 
  17.     # If the key is in added keys, initialize the key in the weights dictionary, with a weight of 2. 
  18.     elif key in added_keys: 
  19.         weights[key] = 2 
  20.     # If the key isn't in added_keys yet, append it. 
  21.     # This ensures that we aren't adding edges with a weight of 1. 
  22.     else
  23.         added_keys.append(key 

一旦上面的代碼運(yùn)行,這個(gè)權(quán)重字典就包含了每?jī)蓚€(gè)機(jī)場(chǎng)之間權(quán)重大于或等于 2 的連線。所以任何機(jī)場(chǎng)有兩個(gè)或者更多連接的路由將會(huì)顯示出來。

  1. # Import networkx and initialize the graph. 
  2. import networkx as nx 
  3. graph = nx.Graph() 
  4. # Keep track of added nodes in this set so we don't add twice. 
  5. nodes = set() 
  6. # Iterate through each edge. 
  7. for k, weight in weights.items(): 
  8.     try: 
  9.         # Split the source and dest ids and convert to integers. 
  10.         source, dest = k.split("_"
  11.         source, dest = [int(source), int(dest)] 
  12.         # Add the source if it isn't in the nodes. 
  13.         if source not in nodes: 
  14.             graph.add_node(source) 
  15.         # Add the dest if it isn't in the nodes. 
  16.         if dest not in nodes: 
  17.             graph.add_node(dest) 
  18.         # Add both source and dest to the nodes set
  19.         # Sets don't allow duplicates. 
  20.         nodes.add(source) 
  21.         nodes.add(dest) 
  22.          
  23.         # Add the edge to the graph. 
  24.         graph.add_edge(source, dest, weight=weight) 
  25.     except (ValueError, IndexError): 
  26.         pass 
  27. pos=nx.spring_layout(graph) 
  28. # Draw the nodes and edges. 
  29. nx.draw_networkx_nodes(graph,pos, node_color='red', node_size=10, alpha=0.8) 
  30. nx.draw_networkx_edges(graph,pos,width=1.0,alpha=1) 
  31. # Show the plot. 
  32. plt.show() 

總結(jié)

有一個(gè)成長(zhǎng)的數(shù)據(jù)可視化的 Python 庫(kù),它可能會(huì)制作任意一種可視化。大多數(shù)庫(kù)基于 matplotlib 構(gòu)建的并且確保一些用例更簡(jiǎn)單。如果你想更深入的學(xué)習(xí)怎樣使用 matplotlib,seaborn 和其他工具來可視化數(shù)據(jù),在這兒檢出其他課程。

責(zé)任編輯:龐桂玉 來源: 36大數(shù)據(jù)
相關(guān)推薦

2020-11-17 08:58:32

開源工具報(bào)表

2017-07-12 15:32:12

大數(shù)據(jù)大數(shù)據(jù)技術(shù)Python

2015-08-26 13:11:54

數(shù)據(jù)Python

2021-01-04 09:52:35

Git開源報(bào)表工具

2020-11-17 16:22:45

開源工具報(bào)表

2020-09-17 12:30:51

Linux比較工具命令

2018-03-28 14:33:33

數(shù)據(jù)分析師工具Spark

2015-07-23 10:49:06

Python工具數(shù)據(jù)科學(xué)

2015-12-02 09:44:04

Python視化工具

2021-04-01 10:22:42

工具Linux文件

2018-09-07 11:12:19

CICD工具

2017-02-14 11:28:29

互聯(lián)網(wǎng) 報(bào)表

2020-09-21 09:50:07

Linux工具命令

2013-12-06 14:09:22

Linux運(yùn)維工具

2024-03-08 12:09:26

數(shù)據(jù)可視化圖表

2019-11-22 08:52:32

MacEvernoteMWeb

2020-05-06 11:45:08

Mac工具語法

2021-01-08 09:00:00

開發(fā)工具技術(shù)

2015-08-24 09:24:17

開源報(bào)表工具

2018-12-26 15:14:56

點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)