99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀利用Python代碼實現(xiàn)數(shù)據(jù)可視化的5種方法詳解
利用Python代碼實現(xiàn)數(shù)據(jù)可視化的5種方法詳解
2018-04-20
收藏

利用Python代碼實現(xiàn)數(shù)據(jù)可視化的5種方法詳解

數(shù)據(jù)科學(xué)家并不遜色于藝術(shù)家。他們用數(shù)據(jù)可視化的方式繪畫,試圖展現(xiàn)數(shù)據(jù)內(nèi)隱藏的模式或表達對數(shù)據(jù)的見解。更有趣的是,一旦接觸到任何可視化的內(nèi)容、數(shù)據(jù)時,人類會有更強烈的知覺、認(rèn)知和交流。

數(shù)據(jù)可視化是數(shù)據(jù)科學(xué)家工作中的重要組成部分。在項目的早期階段,你通常會進行探索性數(shù)據(jù)分析(Exploratory Data Analysis,EDA)以獲取對數(shù)據(jù)的一些理解。創(chuàng)建可視化方法確實有助于使事情變得更加清晰易懂,特別是對于大型、高維數(shù)據(jù)集。在項目結(jié)束時,以清晰、簡潔和引人注目的方式展現(xiàn)最終結(jié)果是非常重要的,因為你的受眾往往是非技術(shù)型客戶,只有這樣他們才可以理解。

Matplotlib 是一個流行的 Python 庫,可以用來很簡單地創(chuàng)建數(shù)據(jù)可視化方案。但每次創(chuàng)建新項目時,設(shè)置數(shù)據(jù)、參數(shù)、圖形和排版都會變得非常繁瑣和麻煩。在這篇博文中,我們將著眼于 5 個數(shù)據(jù)可視化方法,并使用 Python Matplotlib 為他們編寫一些快速簡單的函數(shù)。與此同時,這里有一個很棒的圖表,可用于在工作中選擇正確的可視化方法!

散點圖

散點圖非常適合展示兩個變量之間的關(guān)系,因為你可以直接看到數(shù)據(jù)的原始分布。 如下面第一張圖所示的,你還可以通過對組進行簡單地顏色編碼來查看不同組數(shù)據(jù)的關(guān)系。想要可視化三個變量之間的關(guān)系? 沒問題! 僅需使用另一個參數(shù)(如點大小)就可以對第三個變量進行編碼,如下面的第二張圖所示。

現(xiàn)在開始討論代碼。我們首先用別名 “plt” 導(dǎo)入 Matplotlib 的 pyplot 。要創(chuàng)建一個新的點陣圖,我們可調(diào)用 plt.subplots() 。我們將 x 軸和 y 軸數(shù)據(jù)傳遞給該函數(shù),然后將這些數(shù)據(jù)傳遞給 ax.scatter() 以繪制散點圖。我們還可以設(shè)置點的大小、點顏色和 alpha 透明度。你甚至可以設(shè)置 Y 軸為對數(shù)刻度。標(biāo)題和坐標(biāo)軸上的標(biāo)簽可以專門為該圖設(shè)置。這是一個易于使用的函數(shù),可用于從頭到尾創(chuàng)建散點圖!

import matplotlib.pyplot as pltimport numpy as npdef scatterplot(x_data, y_data, x_label="", y_label="", title="", color = "r", yscale_log=False):
 # Create the plot object
 _, ax = plt.subplots() # Plot the data, set the size (s), color and transparency (alpha)
 # of the points
 ax.scatter(x_data, y_data, s = 10, color = color, alpha = 0.75) if yscale_log == True:
 ax.set_yscale('log') # Label the axes and provide a title
 ax.set_title(title)
 ax.set_xlabel(x_label)
 ax.set_ylabel(y_label)
折線圖

當(dāng)你可以看到一個變量隨著另一個變量明顯變化的時候,比如說它們有一個大的協(xié)方差,那最好使用折線圖。讓我們看一下下面這張圖。我們可以清晰地看到對于所有的主線隨著時間都有大量的變化。使用散點繪制這些將會極其混亂,難以真正明白和看到發(fā)生了什么。折線圖對于這種情況則非常好,因為它們基本上提供給我們兩個變量(百分比和時間)的協(xié)方差的快速總結(jié)。另外,我們也可以通過彩色編碼進行分組。

這里是折線圖的代碼。它和上面的散點圖很相似,只是在一些變量上有小的變化。

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

直方圖

直方圖對于查看(或真正地探索)數(shù)據(jù)點的分布是很有用的。查看下面我們以頻率和 IQ 做的直方圖。我們可以清楚地看到朝中間聚集,并且能看到中位數(shù)是多少。我們也可以看到它呈正態(tài)分布。使用直方圖真得能清晰地呈現(xiàn)出各個組的頻率之間的相對差別。組的使用(離散化)真正地幫助我們看到了“更加宏觀的圖形”,然而當(dāng)我們使用所有沒有離散組的數(shù)據(jù)點時,將對可視化可能造成許多干擾,使得看清真正發(fā)生了什么變得困難。

下面是在 Matplotlib 中的直方圖代碼。有兩個參數(shù)需要注意一下:首先,參數(shù) n_bins 控制我們想要在直方圖中有多少個離散的組。更多的組將給我們提供更加完善的信息,但是也許也會引進干擾,使得我們遠離全局;另一方面,較少的組給我們一種更多的是“鳥瞰圖”和沒有更多細節(jié)的全局圖。其次,參數(shù) cumulative 是一個布爾值,允許我們選擇直方圖是否為累加的,基本上就是選擇是 PDF(Probability Density Function,概率密度函數(shù))還是 CDF(Cumulative Density Function,累積密度函數(shù))。

defhistogram(data, n_bins, cumulative=False, x_label="", y_label = "", title = ""):
 _, ax=plt.subplots()
 ax.hist(data, n_bins=n_bins, cumulative=cumulative, color='#539caf')
 ax.set_ylabel(y_label)
 ax.set_xlabel(x_label)
 ax.set_title(title)

想象一下我們想要比較數(shù)據(jù)中兩個變量的分布。有人可能會想你必須制作兩張直方圖,并且把它們并排放在一起進行比較。然而,實際上有一種更好的辦法:我們可以使用不同的透明度對直方圖進行疊加覆蓋??聪聢D,均勻分布的透明度設(shè)置為 0.5 ,使得我們可以看到他背后的圖形。這樣我們就可以直接在同一張圖表里看到兩個分布。

對于重疊的直方圖,需要設(shè)置一些東西。首先,我們設(shè)置可同時容納不同分布的橫軸范圍。根據(jù)這個范圍和期望的組數(shù),我們可以真正地計算出每個組的寬度。最后,我們在同一張圖上繪制兩個直方圖,其中有一個稍微更透明一些。

# Overlay 2 histograms to compare themdef overlaid_histogram(data1, data2, n_bins = 0, data1_name="", data1_color="#539caf", data2_name="", data2_color="#7663b0", x_label="", y_label="", title=""):
 # Set the bounds for the bins so that the two distributions are fairly compared
 max_nbins = 10
 data_range = [min(min(data1), min(data2)), max(max(data1), max(data2))]
 binwidth = (data_range[1] - data_range[0]) / max_nbins if n_bins == 0
 bins = np.arange(data_range[0], data_range[1] + binwidth, binwidth) else:
 bins = n_bins # Create the plot
 _, ax = plt.subplots()
 ax.hist(data1, bins = bins, color = data1_color, alpha = 1, label = data1_name)
 ax.hist(data2, bins = bins, color = data2_color, alpha = 0.75, label = data2_name)
 ax.set_ylabel(y_label)
 ax.set_xlabel(x_label)
 ax.set_title(title)
 ax.legend(loc = 'best')

柱狀圖

當(dāng)你試圖將類別很少(可能小于10)的分類數(shù)據(jù)可視化的時候,柱狀圖是最有效的。如果我們有太多的分類,那么這些柱狀圖就會非常雜亂,很難理解。柱狀圖對分類數(shù)據(jù)很好,因為你可以很容易地看到基于柱的類別之間的區(qū)別(比如大小);分類也很容易劃分和用顏色進行編碼。我們將會看到三種不同類型的柱狀圖:常規(guī)的,分組的,堆疊的。在我們進行的過程中,請查看圖形下面的代碼。

常規(guī)的柱狀圖如下面的圖1。在 barplot() 函數(shù)中,xdata 表示 x 軸上的標(biāo)記,ydata 表示 y 軸上的桿高度。誤差條是一條以每條柱為中心的額外的線,可以畫出標(biāo)準(zhǔn)偏差。

分組的柱狀圖讓我們可以比較多個分類變量??纯聪旅娴膱D2。我們比較的第一個變量是不同組的分?jǐn)?shù)是如何變化的(組是G1,G2,……等等)。我們也在比較性別本身和顏色代碼??匆幌麓a,y_data_list 變量實際上是一個 y 元素為列表的列表,其中每個子列表代表一個不同的組。然后我們對每個組進行循環(huán),對于每一個組,我們在 x 軸上畫出每一個標(biāo)記;每個組都用彩色進行編碼。

堆疊柱狀圖可以很好地觀察不同變量的分類。在圖3的堆疊柱狀圖中,我們比較了每天的服務(wù)器負(fù)載。通過顏色編碼后的堆棧圖,我們可以很容易地看到和理解哪些服務(wù)器每天工作最多,以及與其他服務(wù)器進行比較負(fù)載情況如何。此代碼的代碼與分組的條形圖相同。我們循環(huán)遍歷每一組,但這次我們把新柱放在舊柱上,而不是放在它們的旁邊。

def barplot(x_data, y_data, error_data, x_label="", y_label="", title=""):
 _, ax = plt.subplots()
 # Draw bars, position them in the center of the tick mark on the x-axis
 ax.bar(x_data, y_data, color = '#539caf', align = 'center')
 # Draw error bars to show standard deviation, set ls to 'none'
 # to remove line between points
 ax.errorbar(x_data, y_data, yerr = error_data, color = '#297083', ls = 'none', lw = 2, capthick = 2)
 ax.set_ylabel(y_label)
 ax.set_xlabel(x_label)
 ax.set_title(title)
 
def stackedbarplot(x_data, y_data_list, colors, y_data_names="", x_label="", y_label="", title=""):
 _, ax = plt.subplots()
 # Draw bars, one category at a time
 for i in range(0, len(y_data_list)):
 if i == 0:
  ax.bar(x_data, y_data_list[i], color = colors[i], align = 'center', label = y_data_names[i])
 else:
  # For each category after the first, the bottom of the
  # bar will be the top of the last category
  ax.bar(x_data, y_data_list[i], color = colors[i], bottom = y_data_list[i - 1], align = 'center', label = y_data_names[i])
 ax.set_ylabel(y_label)
 ax.set_xlabel(x_label)
 ax.set_title(title)
 ax.legend(loc = 'upper right')
 
def groupedbarplot(x_data, y_data_list, colors, y_data_names="", x_label="", y_label="", title=""):
 _, ax = plt.subplots()
 # Total width for all bars at one x location
 total_width = 0.8
 # Width of each individual bar
 ind_width = total_width / len(y_data_list)
 # This centers each cluster of bars about the x tick mark
 alteration = np.arange(-(total_width/2), total_width/2, ind_width)
 
 # Draw bars, one category at a time
 for i in range(0, len(y_data_list)):
 # Move the bar to the right on the x-axis so it doesn't
 # overlap with previously drawn ones
 ax.bar(x_data + alteration[i], y_data_list[i], color = colors[i], label = y_data_names[i], width = ind_width)
 ax.set_ylabel(y_label)
 ax.set_xlabel(x_label)
 ax.set_title(title)
 ax.legend(loc = 'upper right')
箱形圖

我們之前看了直方圖,它很好地可視化了變量的分布。但是如果我們需要更多的信息呢?也許我們想要更清晰的看到標(biāo)準(zhǔn)偏差?也許中值與均值有很大不同,我們有很多離群值?如果有這樣的偏移和許多值都集中在一邊呢?

這就是箱形圖所適合干的事情了。箱形圖給我們提供了上面所有的信息。實線框的底部和頂部總是第一個和第三個四分位(比如 25% 和 75% 的數(shù)據(jù)),箱體中的橫線總是第二個四分位(中位數(shù))。像胡須一樣的線(虛線和結(jié)尾的條線)從這個箱體伸出,顯示數(shù)據(jù)的范圍。

由于每個組/變量的框圖都是分別繪制的,所以很容易設(shè)置。xdata 是一個組/變量的列表。Matplotlib 庫的 boxplot() 函數(shù)為 ydata 中的每一列或每一個向量繪制一個箱體。因此,xdata 中的每個值對應(yīng)于 ydata 中的一個列/向量。我們所要設(shè)置的就是箱體的美觀。

def boxplot(x_data, y_data, base_color="#539caf", median_color="#297083", x_label="", y_label="", title=""):
 _, ax = plt.subplots()
 # Draw boxplots, specifying desired style
 ax.boxplot(y_data
    # patch_artist must be True to control box fill
    , patch_artist = True
    # Properties of median line
    , medianprops = {'color': median_color}
    # Properties of box
    , boxprops = {'color': base_color, 'facecolor': base_color}
    # Properties of whiskers
    , whiskerprops = {'color': base_color}
    # Properties of whisker caps
    , capprops = {'color': base_color})
 
 # By default, the tick label starts at 1 and increments by 1 for
 # each box drawn. This sets the labels to the ones we want
 ax.set_xticklabels(x_data)
 ax.set_ylabel(y_label)
 ax.set_xlabel(x_label)
 ax.set_title(title)
結(jié)語使用 Matplotlib 有 5 個快速簡單的數(shù)據(jù)可視化方法。將相關(guān)事務(wù)抽象成函數(shù)總是會使你的代碼更易于閱讀和使用!我希望你喜歡這篇文章,并且學(xué)到了一些新的有用的技巧



數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務(wù)器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }