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

5種快速易用的Python Matplotlib數(shù)據(jù)可視化方法

大數(shù)據(jù) 數(shù)據(jù)可視化
在項(xiàng)目的早期階段,我們通常需要進(jìn)行探索性數(shù)據(jù)分析來獲得對(duì)數(shù)據(jù)的洞察。通過數(shù)據(jù)可視化可以讓該過程變得更加清晰易懂,尤其是在處理大規(guī)模、高維度數(shù)據(jù)集時(shí)。本文我們介紹了最基本的5種數(shù)據(jù)可視化圖表,在展示了它們的優(yōu)劣點(diǎn)后,我們還提供了繪制對(duì)應(yīng)圖表的Matplotlib代碼。

數(shù)據(jù)可視化是數(shù)據(jù)科學(xué)家工作的重要部分。在項(xiàng)目的早期階段,我們通常需要進(jìn)行探索性數(shù)據(jù)分析來獲得對(duì)數(shù)據(jù)的洞察。通過數(shù)據(jù)可視化可以讓該過程變得更加清晰易懂,尤其是在處理大規(guī)模、高維度數(shù)據(jù)集時(shí)。在本文中,我們介紹了最基本的 5 種數(shù)據(jù)可視化圖表,在展示了它們的優(yōu)劣點(diǎn)后,我們還提供了繪制對(duì)應(yīng)圖表的 Matplotlib 代碼。

Matplotlib 是一個(gè)很流行的 Python 庫,可以幫助你快速方便地構(gòu)建數(shù)據(jù)可視化圖表。然而,每次啟動(dòng)一個(gè)新項(xiàng)目時(shí)都需要重新設(shè)置數(shù)據(jù)、參數(shù)、圖形和繪圖方式是非常枯燥無聊的。本文將介紹 5 種數(shù)據(jù)可視化方法,并用 Python 和 Matplotlib 寫一些快速易用的可視化函數(shù)。下圖展示了選擇正確可視化方法的導(dǎo)向圖。 


選擇正確可視化方法的導(dǎo)向圖。

散點(diǎn)圖

由于可以直接看到原始數(shù)據(jù)的分布,散點(diǎn)圖對(duì)于展示兩個(gè)變量之間的關(guān)系非常有用。你還可以通過用顏色將數(shù)據(jù)分組來觀察不同組數(shù)據(jù)之間的關(guān)系,如下圖所示。你還可以添加另一個(gè)參數(shù),如數(shù)據(jù)點(diǎn)的半徑來編碼第三個(gè)變量,從而可視化三個(gè)變量之間的關(guān)系,如下方第二個(gè)圖所示。 


用顏色分組的散點(diǎn)圖。

用顏色分組的散點(diǎn)圖,點(diǎn)半徑作為第三個(gè)變量表示國(guó)家規(guī)模。

接下來是代碼部分。我們首先將 Matplotlib 的 pyplot 導(dǎo)入為 plt,并調(diào)用函數(shù) plt.subplots() 來創(chuàng)建新的圖。我們將 x 軸和 y 軸的數(shù)據(jù)傳遞給該函數(shù),然后將其傳遞給 ax.scatter() 來畫出散點(diǎn)圖。我們還可以設(shè)置點(diǎn)半徑、點(diǎn)顏色和 alpha 透明度,甚至將 y 軸設(shè)置為對(duì)數(shù)尺寸,***為圖指定標(biāo)題和坐標(biāo)軸標(biāo)簽。

  1. import matplotlib.pyplot as plt 
  2. import numpy as np 
  3.  
  4. def scatterplot(x_data, y_data, x_label="", y_label="", title="", color = "r", yscale_log=False): 
  5.  
  6.     # Create the plot object 
  7.     _, ax = plt.subplots() 
  8.  
  9.     # Plot the data, set the size (s), color and transparency (alpha) 
  10.     # of the points 
  11.     ax.scatter(x_data, y_data, s = 10, color = color, alpha = 0.75) 
  12.  
  13.     if yscale_log == True
  14.         ax.set_yscale('log'
  15.  
  16.     # Label the axes and provide a title 
  17.     ax.set_title(title) 
  18.     ax.set_xlabel(x_label) 
  19.     ax.set_ylabel(y_label) 

線圖

當(dāng)一個(gè)變量隨另一個(gè)變量的變化而變化的幅度很大時(shí),即它們有很高的協(xié)方差時(shí),線圖非常好用。如下圖所示,我們可以看到,所有專業(yè)課程的相對(duì)百分?jǐn)?shù)隨年代的變化的幅度都很大。用散點(diǎn)圖來畫這些數(shù)據(jù)將變得非常雜亂無章,而難以看清其本質(zhì)。線圖非常適合這種情況,因?yàn)樗梢钥焖俚乜偨Y(jié)出兩個(gè)變量的協(xié)方差。在這里,我們也可以用顏色將數(shù)據(jù)分組。 


線圖示例。

以下是線圖的實(shí)現(xiàn)代碼,和散點(diǎn)圖的代碼結(jié)構(gòu)很相似,只在變量設(shè)置上有少許變化。

  1. def lineplot(x_data, y_data, x_label="", y_label="", title=""): 
  2.     # Create the plot object 
  3.     _, ax = plt.subplots() 
  4.  
  5.     # Plot the best fit line, set the linewidth (lw), color and 
  6.     # transparency (alpha) of the line 
  7.     ax.plot(x_data, y_data, lw = 2, color = '#539caf', alpha = 1) 
  8.  
  9.     # Label the axes and provide a title 
  10.     ax.set_title(title) 
  11.     ax.set_xlabel(x_label) 
  12.     ax.set_ylabel(y_label) 

直方圖

直方圖對(duì)于觀察或真正了解數(shù)據(jù)點(diǎn)的分布十分有用。以下為我們繪制的頻率與 IQ 的直方圖,我們可以直觀地了解分布的集中度(方差)與中位數(shù),也可以了解到該分布的形狀近似服從于高斯分布。使用這種柱形(而不是散點(diǎn)圖等)可以清楚地可視化每一個(gè)箱體(X 軸的一個(gè)等距區(qū)間)間頻率的變化。使用箱體(離散化)確實(shí)能幫助我們觀察到「更完整的圖像」,因?yàn)槭褂盟袛?shù)據(jù)點(diǎn)而不采用離散化會(huì)觀察不到近似的數(shù)據(jù)分布,可能在可視化中存在許多噪聲,使其只能近似地而不能描述真正的數(shù)據(jù)分布。 

直方圖案例

下面展示了 Matplotlib 中繪制直方圖的代碼。這里有兩個(gè)步驟需要注意,首先,n_bins 參數(shù)控制直方圖的箱體數(shù)量或離散化程度。更多的箱體或柱體能給我們提供更多的信息,但同樣也會(huì)引入噪聲并使我們觀察到的全局分布圖像變得不太規(guī)則。而更少的箱體將給我們更多的全局信息,我們可以在缺少細(xì)節(jié)信息的情況下觀察到整體分布的形狀。其次,cumulative 參數(shù)是一個(gè)布爾值,它允許我們選擇直方圖是不是累積的,即選擇概率密度函數(shù)(PDF)或累積密度函數(shù)(CDF)。

  1. def histogram(data, n_bins, cumulative=False, x_label = "", y_label = "", title = ""): 
  2.     _, ax = plt.subplots() 
  3.     ax.hist(data, n_bins = n_bins, cumulative = cumulative, color = '#539caf'
  4.     ax.set_ylabel(y_label) 
  5.     ax.set_xlabel(x_label) 
  6.     ax.set_title(title)

如果我們希望比較數(shù)據(jù)中兩個(gè)變量的分布,有人可能會(huì)認(rèn)為我們需要制作兩個(gè)獨(dú)立的直方圖,并將它們拼接在一起而進(jìn)行比較。但實(shí)際上 Matplotlib 有更好的方法,我們可以用不同的透明度疊加多個(gè)直方圖。如下圖所示,均勻分布設(shè)置透明度為 0.5,因此我們就能將其疊加在高斯分布上,這允許用戶在同一圖表上繪制并比較兩個(gè)分布。 


疊加直方圖

在疊加直方圖的代碼中,我們需要注意幾個(gè)問題。首先,我們?cè)O(shè)定的水平區(qū)間要同時(shí)滿足兩個(gè)變量的分布。根據(jù)水平區(qū)間的范圍和箱體數(shù),我們可以計(jì)算每個(gè)箱體的寬度。其次,我們?cè)谝粋€(gè)圖表上繪制兩個(gè)直方圖,需要保證一個(gè)直方圖存在更大的透明度。

  1. # Overlay 2 histograms to compare them 
  2. def overlaid_histogram(data1, data2, n_bins = 0, data1_name="", data1_color="#539caf", data2_name="", data2_color="#7663b0", x_label="", y_label="", title=""): 
  3.     # Set the bounds for the bins so that the two distributions are fairly compared 
  4.     max_nbins = 10 
  5.     data_range = [min(min(data1), min(data2)), max(max(data1), max(data2))] 
  6.     binwidth = (data_range[1] - data_range[0]) / max_nbins 
  7.  
  8.  
  9.     if n_bins == 0 
  10.         bins = np.arange(data_range[0], data_range[1] + binwidth, binwidth) 
  11.     else:  
  12.         bins = n_bins 
  13.  
  14.     # Create the plot 
  15.     _, ax = plt.subplots() 
  16.     ax.hist(data1, bins = bins, color = data1_color, alpha = 1, label = data1_name) 
  17.     ax.hist(data2, bins = bins, color = data2_color, alpha = 0.75, label = data2_name) 
  18.     ax.set_ylabel(y_label) 
  19.     ax.set_xlabel(x_label) 
  20.     ax.set_title(title) 
  21.     ax.legend(loc = 'best'

條形圖

當(dāng)對(duì)類別數(shù)很少(<10)的分類數(shù)據(jù)進(jìn)行可視化時(shí),條形圖是最有效的。當(dāng)類別數(shù)太多時(shí),條形圖將變得很雜亂,難以理解。你可以基于條形的數(shù)量觀察不同類別之間的區(qū)別,不同的類別可以輕易地分離以及用顏色分組。我們將介紹三種類型的條形圖:常規(guī)、分組和堆疊條形圖。

常規(guī)條形圖如圖 1 所示。在 barplot() 函數(shù)中,x_data 表示 x 軸上的不同類別,y_data 表示 y 軸上的條形高度。誤差條形是額外添加在每個(gè)條形中心上的線,可用于表示標(biāo)準(zhǔn)差。 


常規(guī)條形圖

分組條形圖允許我們比較多個(gè)類別變量。如下圖所示,我們***個(gè)變量會(huì)隨不同的分組(G1、G2 等)而變化,我們?cè)诿恳唤M上比較不同的性別。正如代碼所示,y_data_list 變量現(xiàn)在實(shí)際上是一組列表,其中每個(gè)子列表代表了一個(gè)不同的組。然后我們循環(huán)地遍歷每一個(gè)組,并在 X 軸上繪制柱體和對(duì)應(yīng)的值,每一個(gè)分組的不同類別將使用不同的顏色表示。 


分組條形圖

堆疊條形圖非常適合于可視化不同變量的分類構(gòu)成。在下面的堆疊條形圖中,我們比較了工作日的服務(wù)器負(fù)載。通過使用不同顏色的方塊堆疊在同一條形圖上,我們可以輕松查看并了解哪臺(tái)服務(wù)器每天的工作效率***,和同一服務(wù)器在不同天數(shù)的負(fù)載大小。繪制該圖的代碼與分組條形圖有相同的風(fēng)格,我們循環(huán)地遍歷每一組,但我們這次在舊的柱體之上而不是旁邊繪制新的柱體。 


堆疊條形圖

  1. def barplot(x_data, y_data, error_data, x_label="", y_label="", title=""): 
  2.     _, ax = plt.subplots() 
  3.     # Draw bars, position them in the center of the tick mark on the x-axis 
  4.     ax.bar(x_data, y_data, color = '#539caf', align = 'center'
  5.     # Draw error bars to show standard deviation, set ls to 'none' 
  6.     # to remove line between points 
  7.     ax.errorbar(x_data, y_data, yerr = error_data, color = '#297083', ls = 'none', lw = 2, capthick = 2) 
  8.     ax.set_ylabel(y_label) 
  9.     ax.set_xlabel(x_label) 
  10.     ax.set_title(title) 
  11.  
  12.  
  13.  
  14. def stackedbarplot(x_data, y_data_list, colors, y_data_names="", x_label="", y_label="", title=""): 
  15.     _, ax = plt.subplots() 
  16.     # Draw bars, one category at a time 
  17.     for i in range(0, len(y_data_list)): 
  18.         if i == 0: 
  19.             ax.bar(x_data, y_data_list[i], color = colors[i], align = 'center', label = y_data_names[i]) 
  20.         else
  21.             # For each category after the first, the bottom of the 
  22.             # bar will be the top of the last category 
  23.             ax.bar(x_data, y_data_list[i], color = colors[i], bottom = y_data_list[i - 1], align = 'center', label = y_data_names[i]) 
  24.     ax.set_ylabel(y_label) 
  25.     ax.set_xlabel(x_label) 
  26.     ax.set_title(title) 
  27.     ax.legend(loc = 'upper right'
  28.  
  29.  
  30.  
  31. def groupedbarplot(x_data, y_data_list, colors, y_data_names="", x_label="", y_label="", title=""): 
  32.     _, ax = plt.subplots() 
  33.     # Total width for all bars at one x location 
  34.     total_width = 0.8 
  35.     # Width of each individual bar 
  36.     ind_width = total_width / len(y_data_list) 
  37.     # This centers each cluster of bars about the x tick mark 
  38.     alteration = np.arange(-(total_width/2), total_width/2, ind_width) 
  39.  
  40.  
  41.     # Draw bars, one category at a time 
  42.     for i in range(0, len(y_data_list)): 
  43.         # Move the bar to the right on the x-axis so it doesn't 
  44.         # overlap with previously drawn ones 
  45.         ax.bar(x_data + alteration[i], y_data_list[i], color = colors[i], label = y_data_names[i], width = ind_width) 
  46.     ax.set_ylabel(y_label) 
  47.     ax.set_xlabel(x_label) 
  48.     ax.set_title(title) 
  49.     ax.legend(loc = 'upper right'

箱線圖

上述的直方圖對(duì)于可視化變量分布非常有用,但當(dāng)我們需要更多信息時(shí),怎么辦?我們可能需要清晰地可視化標(biāo)準(zhǔn)差,也可能出現(xiàn)中位數(shù)和平均值差值很大的情況(有很多異常值),因此需要更細(xì)致的信息。還可能出現(xiàn)數(shù)據(jù)分布非常不均勻的情況等等。

箱線圖可以給我們以上需要的所有信息。實(shí)線箱的底部表示***個(gè)四分位數(shù),頂部表示第三個(gè)四分位數(shù),箱內(nèi)的線表示第二個(gè)四分位數(shù)(中位數(shù))。虛線表示數(shù)據(jù)的分布范圍。

由于箱線圖是對(duì)單個(gè)變量的可視化,其設(shè)置很簡(jiǎn)單。x_data 是變量的列表。Matplotlib 函數(shù) boxplot() 為 y_data 的每一列或 y_data 序列中的每個(gè)向量繪制一個(gè)箱線圖,因此 x_data 中的每個(gè)值對(duì)應(yīng) y_data 中的一列/一個(gè)向量。 


箱線圖示例。
  1. def boxplot(x_data, y_data, base_color="#539caf", median_color="#297083", x_label="", y_label="", title=""): 
  2.     _, ax = plt.subplots() 
  3.  
  4.     # Draw boxplots, specifying desired style 
  5.     ax.boxplot(y_data 
  6.                # patch_artist must be True to control box fill 
  7.                , patch_artist = True 
  8.                # Properties of median line 
  9.                , medianprops = {'color': median_color} 
  10.                # Properties of box 
  11.                , boxprops = {'color': base_color, 'facecolor': base_color} 
  12.                # Properties of whiskers 
  13.                , whiskerprops = {'color': base_color} 
  14.                # Properties of whisker caps 
  15.                , capprops = {'color': base_color}) 
  16.  
  17.     # By default, the tick label starts at 1 and increments by 1 for 
  18.     # each box drawn. This sets the labels to the ones we want 
  19.     ax.set_xticklabels(x_data) 
  20.     ax.set_ylabel(y_label) 
  21.     ax.set_xlabel(x_label) 
  22.     ax.set_title(title) 

箱線圖代碼

結(jié)論

本文介紹了 5 種方便易用的 Matplotlib 數(shù)據(jù)可視化方法。將可視化過程抽象為函數(shù)可以令代碼變得易讀和易用。Hope you enjoyed!

責(zé)任編輯:未麗燕 來源: 機(jī)器之心編譯
相關(guān)推薦

2022-09-08 16:28:53

Python數(shù)據(jù)可視化機(jī)器學(xué)習(xí)

2018-03-24 21:38:54

Python數(shù)據(jù)庫數(shù)據(jù)可視化

2018-03-26 14:20:23

PythonMatplotlib數(shù)據(jù)可視化

2018-11-26 18:45:22

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

2019-09-12 09:00:32

數(shù)據(jù)可視化熱圖數(shù)據(jù)集

2024-12-24 12:00:00

Matplotlib可視化分析Python

2020-03-04 14:15:29

Python數(shù)據(jù)可視化代碼

2024-08-20 18:16:49

數(shù)據(jù)可視化Python

2024-10-24 16:43:15

2018-04-24 16:01:46

代碼數(shù)據(jù)可視化Python

2020-03-11 14:39:26

數(shù)據(jù)可視化地圖可視化地理信息

2020-07-16 15:20:37

MatplotlibPython可視化

2018-07-23 16:54:09

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

2017-06-14 18:33:17

大數(shù)據(jù)可視化方法

2024-12-25 16:35:53

2014-05-16 09:52:16

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

2017-10-14 13:54:26

數(shù)據(jù)可視化數(shù)據(jù)信息可視化

2015-09-21 09:27:25

數(shù)據(jù)可視化錯(cuò)誤

2017-10-31 09:38:53

大數(shù)據(jù)數(shù)據(jù)可視化Python

2017-08-15 18:55:57

大數(shù)據(jù)數(shù)據(jù)可視化圖表
點(diǎn)贊
收藏

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