数据可视化(箱线图、直方图、散点图、联合分布图)
數據可視化
箱線圖可視化
箱線圖(Box plot)也稱箱須圖(Box-whisker Plot)、箱線圖、盒圖,可以用來反映一組或多組連續型定量數據分布的中心位置和散布范圍。
連續型數據:在一定區間內可以任意取值的變量叫連續變量,其數值是連續不斷的??梢暬@類數據的圖表主要有箱形圖和直方圖。
離散型數據:數值只能用自然數或整數單位計算的則為離散變量。大多數圖表可視化的都是這類數據,比如柱狀圖、折線圖等。
箱線圖中的數據含義
離散度度量:
- 四分位數:
- 四分位數:Q1(第25百分位),Q3(第75百分位)
- 四分位數極差:IQR = Q3 - Q1
- 五點概況:
- min,Q1,median,Q3,max
- 箱線圖(boxplot):min,Q1,median,Q3,max
- 離群點:通常情況下,一個值高于或低于1.5xIQR
m a x = Q 3 + 1.5 × I Q R m i n = Q 1 ? 1.5 × I Q R \begin{align} max = Q3 + 1.5 \times IQR \end{align} \\ \begin{align} min = Q1 -1.5 \times IQR \end{align} max=Q3+1.5×IQR??min=Q1?1.5×IQR??
箱線圖繪制箱線圖
參考:https://blog.csdn.net/H_lukong/article/details/90139700
參考:https://www.cnblogs.com/star-zhao/p/9847082.html
參考:https://blog.csdn.net/weixin_44052055/article/details/121442449
這里對matplotlib中的boxplot()函數中的參數做以下記錄。主要需要知道x,vert,
使用boxblot()函數繪制箱線圖,這里繪制箱線圖需要傳入數據給x,其次是labels信息,這個也是需要傳入參數的,默認labels是[1,2,3···]這樣的信息。
import pandas as pd import matplotlib.pyplot as pltfilename = 'iris_dataset/iris.csv' dataset = pd.read_csv(filename) print(dataset.describe()) # 會計算每一列數值的mean,std,min, 25%,50%,75%,max的值labels = dataset.columns[1:5] fig, ax = plt.subplots() plt.grid(True, color='Blue') ax.boxplot(x=dataset.iloc[:, 1:5],medianprops={'color':'red', 'linewidth':'1.5'},meanline=True,showmeans=True,meanprops={'color': 'blue', 'ls': '--', 'linewidth': '1.5'},flierprops={'marker': 'o', 'markerfacecolor': 'red', 'markersize': 10},labels=labels)plt.show()
使用pandas.DataFrame對象的plot()函數也可以繪制箱線圖。首先,我們使用pandas來讀取一個.csv表格,這些數據就被存儲到一個DataFrame對象的實例之中。而DataFrame對象有一個plot()函數,可以繪制圖像。在方法中,我們可以傳入數據給參數data,也可以不用傳入參數,因為對象的實例本身也是數據;通過傳入不同的值給kind參數,我們可以繪制多種圖像,kind={‘hist’, ‘boxplot’, ‘sctter’, …}等值,我們也可以通過colorDic來對箱線圖的樣式進行控制,包括箱體boxes的顏色,whisker須線的顏色,medians中位數線的顏色,以及上下最大(小)值caps的顏色。
這里,dataset.iloc[:, 1:5]就是傳入plot函數中的數據,實際上傳入的數據是Sepal.Length Sepal.Width Petal.Length Petal.Width,而dataset.iloc[:, 1:5]本身仍是一個DataFrame的對象:<class ‘pandas.core.frame.DataFrame’>。這一點很重要,如果想要這么使用,必須確保plot前面的對象是一個DataFrame的對象。
import pandas as pd import matplotlib.pyplot as pltfilename = 'iris_dataset/iris.csv' dataset = pd.read_csv(filename)colorDic = dict(boxes='DarkGreen', whiskers='DarkOrange', medians='DarkBlue', caps='Gray') dataset.iloc[:, 1:5].plot(kind='box', color=colorDic, sym='ro')這是函數的其他一些參數。
Parameters----------data : Series or DataFrameThe object for which the method is called.x : label or position, default NoneOnly used if data is a DataFrame.y : label, position or list of label, positions, default NoneAllows plotting of one column versus another. Only used if data is aDataFrame.kind : strThe kind of plot to produce:- 'line' : line plot (default)- 'bar' : vertical bar plot- 'barh' : horizontal bar plot- 'hist' : histogram- 'box' : boxplot- 'kde' : Kernel Density Estimation plot- 'density' : same as 'kde'- 'area' : area plot- 'pie' : pie plot- 'scatter' : scatter plot (DataFrame only)- 'hexbin' : hexbin plot (DataFrame only)ax : matplotlib axes object, default NoneAn axes of the current figure.subplots : bool, default FalseMake separate subplots for each column.sharex : bool, default True if ax is None else FalseIn case ``subplots=True``, share x axis and set some x axis labelsto invisible; defaults to True if ax is None otherwise False ifan ax is passed in; Be aware, that passing in both an ax and``sharex=True`` will alter all x axis labels for all axis in a figure.sharey : bool, default FalseIn case ``subplots=True``, share y axis and set some y axis labels to invisible.layout : tuple, optional(rows, columns) for the layout of subplots.figsize : a tuple (width, height) in inchesSize of a figure object.use_index : bool, default TrueUse index as ticks for x axis.title : str or listTitle to use for the plot. If a string is passed, print the stringat the top of the figure. If a list is passed and `subplots` isTrue, print each item in the list above the corresponding subplot.grid : bool, default None (matlab style default)Axis grid lines.legend : bool or {'reverse'}Place legend on axis subplots.style : list or dictThe matplotlib line style per column.logx : bool or 'sym', default FalseUse log scaling or symlog scaling on x axis... versionchanged:: 0.25.0logy : bool or 'sym' default FalseUse log scaling or symlog scaling on y axis... versionchanged:: 0.25.0loglog : bool or 'sym', default FalseUse log scaling or symlog scaling on both x and y axes... versionchanged:: 0.25.0xticks : sequenceValues to use for the xticks.yticks : sequenceValues to use for the yticks.xlim : 2-tuple/listSet the x limits of the current axes.ylim : 2-tuple/listSet the y limits of the current axes.xlabel : label, optionalName to use for the xlabel on x-axis. Default uses index name as xlabel, or thex-column name for planar plots... versionadded:: 1.1.0.. versionchanged:: 1.2.0Now applicable to planar plots (`scatter`, `hexbin`).ylabel : label, optionalName to use for the ylabel on y-axis. Default will show no ylabel, or they-column name for planar plots... versionadded:: 1.1.0.. versionchanged:: 1.2.0Now applicable to planar plots (`scatter`, `hexbin`).rot : int, default NoneRotation for ticks (xticks for vertical, yticks for horizontalplots).fontsize : int, default NoneFont size for xticks and yticks.colormap : str or matplotlib colormap object, default NoneColormap to select colors from. If string, load colormap with thatname from matplotlib.colorbar : bool, optionalIf True, plot colorbar (only relevant for 'scatter' and 'hexbin'plots).position : floatSpecify relative alignments for bar plot layout.From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5(center).table : bool, Series or DataFrame, default FalseIf True, draw a table using the data in the DataFrame and the datawill be transposed to meet matplotlib's default layout.If a Series or DataFrame is passed, use passed data to draw atable.yerr : DataFrame, Series, array-like, dict and strSee :ref:`Plotting with Error Bars <visualization.errorbars>` fordetail.xerr : DataFrame, Series, array-like, dict and strEquivalent to yerr.stacked : bool, default False in line and bar plots, and True in area plotIf True, create stacked plot.sort_columns : bool, default FalseSort column names to determine plot ordering.secondary_y : bool or sequence, default FalseWhether to plot on the secondary y-axis if a list/tuple, whichcolumns to plot on secondary y-axis.mark_right : bool, default TrueWhen using a secondary_y axis, automatically mark the columnlabels with "(right)" in the legend.include_bool : bool, default is FalseIf True, boolean values can be plotted.backend : str, default NoneBackend to use instead of the backend specified in the option``plotting.backend``. For instance, 'matplotlib'. Alternatively, tospecify the ``plotting.backend`` for the whole session, set``pd.options.plotting.backend``... versionadded:: 1.0.0
這是根據鳶尾花數據繪制的箱線圖,這里紅色實線是數據均值線,藍色虛線是中位數線。從箱線圖中可以看到花萼寬度(Sepal.Width)有一些離群值,其他屬性沒有離群值點。同樣花萼寬度(Sepal.Width)的數據也比較集中,尤其是箱體比較扁?;ㄝ嚅L度、花萼寬度、花瓣寬度的中位數與均值距離較近,花瓣長度(Petal.Length)的均值和中位數有很大差別。
繪制直方圖
參考:https://blog.csdn.net/H_lukong/article/details/90139700
參考:https://blog.cnblogs.com/star-zhao/p/9847082.html
參考:https://blog.csdn.net/Arwen_H/article/details/81985567
第三個,對參數有較為詳細的解釋。
上述這段代碼是利用Pandas.DataFrame對象的plot方法來繪圖,
我們也可以使用專門的繪圖庫。matplotlib.pyplot來進行繪制,
import pandas as pd import matplotlib.pyplot as pltfilename = 'iris_dataset/iris.csv' dataset = pd.read_csv(filename) # 使用matplotlib.pyplot來進行繪制直方圖,這種直方圖我認為比直接用Pandas.DataFrame的plot方法有更多細節可以控制, fig, ax = plt.subplots() ax.hist(dataset['Sepal.Length'], bins=10, color='blue', label='Sepal.Length') ax.hist(dataset['Sepal.Width'], bins=10, color='orange', label='Sepal.Width') ax.hist(dataset['Petal.Length'], bins=10, color='green', label='Petal.Length') ax.hist(dataset['Petal.Width'], bins=10, color='red', label='Petal.Width') plt.legend() plt.show()這里面的bins有一些不同,對于Pandas.DataFrame的直方圖,似乎是統計了所有屬性,然后得到一個整個空間的取值范圍,然后再劃分bins。而對于matplotlib.pyplot方法中,我是單獨傳一列屬性進入,所以也只對單獨傳入的屬性統計取值范圍劃分bins。這里的bins參數值得研究一下。
bins:整數值或序列。如果bins為整數值,則bins為柱子個數,根據數據的取值范圍和柱子個數bins計算每個柱子的范圍值,柱寬=(x.max()-x.min())/bins。如果bins取值為序列,則該序列給出每個柱子的范圍值(即邊緣)。除最后一個柱子外,其他柱子的取值范圍均為半開(左閉右開)。
這里我特意貼出了畫在一起的直方圖和單屬性直方圖組圖。如果想仔細分析單個屬性,還是單屬性直方圖更為恰當?在第一張直方圖的繪制中,可以看到有一些屬性的圖像是被另一屬性的圖像覆蓋了一部分。這樣有什么意義呢?分類算法特征分析:我們可以看到花瓣長度在3個類別下的分布具有差異。
散點圖
參考:https://blog.csdn.net/H_lukong/article/details/90139700
參考:https://www.cnblogs.com/star-zhao/p/9847082.html
Pandas.DataFrame對象的plot方法,在使用時,令參數kind='sctter’即可。值得注意的是,散點圖是描述的兩個屬性之間的相關性,是一個二維圖,需要一個x,y,這兩個值是需要自己進行指定的。
import pandas as pd import matplotlib.pyplot as pltfilename = 'iris_dataset/iris.csv' dataset = pd.read_csv(filename)# 利用Pandas進行繪制散點圖的重要參數包括x,y,kind,size,color,colormap,marker,label dataset.plot(x='Sepal.Length', y='Sepal.Width', kind='scatter', marker='x') pkt.show()color屬性可以是表中的一個屬性列,但是這個屬性列必須是數字或者是顏色值,由于我這里的’Species’是str型數據,所以會報錯,所以這里,如果想再使用不同顏色對不同類別進行上色,需要將類別屬性數值化。
# color還可以是一列屬性 可以與colormap共同使用, # 'c' argument must be a color, a sequence of colors, or a sequence of numbers, not str # dataset.plot(x='Sepal.Length', y='SePal.Width', c='Species', kind='scatter', colormap='viridis')這里的三種顏色分別代表鳶尾花的三種子類setosa,versicolor和virginica,深紫色是setosa,versicolor是綠色,viginica是黃色。
import pandas as pd import matplotlib.pyplot as pltfilename = 'iris_dataset/iris2.csv' dataset = pd.read_csv(filename)# 散布圖矩陣pandas.plotting.scatter_matrix, diagonal 取值只能是{‘hist’, 'kde'},hist表示直方圖,kde表示核密度估計(kernel Density Estimation) # 函數原型聲明scatter_matrix(frame, alpha=0.5, c,figsize=None, ax=None, diagonal='hist', marker='.', density_kwds=None,hist_kwds=None, range_padding=0.05, **kwds) # ax, 可選一般為None,說明散布圖也可以作為子圖存在 pd.plotting.scatter_matrix(dataset.iloc[:, 1:5], diagonal='kde', color='red', alpha=0.3, ) plt.show()從散布圖矩陣,可以看出各個屬性之間的相關性,鳶尾花數據集iris.csv共有四個屬性花瓣長度(Petal.Length)、花瓣寬度(Petal.Width)、花萼長度(Sepal.Length)、花萼寬度(Sepal.Width),故散布圖矩陣共有16張子圖。屬性a與屬性a所畫的是核密度估計曲線圖,屬性a與屬性b之間所畫的是散點圖。根據散點圖矩陣,可以看出,花瓣長度(Petal.Length)和花萼寬度(Petal.Width)存在非常明顯的線性相關?;ò觊L度(Petal.Length)與花萼長度(Sepal.Length)、以及花瓣寬度(Petal.Width)與花萼長度(Petal.Length)之間存在著一定的線性相關,這種線性相關與鳶尾花的品種存在著某些關系?。
利用matplotlib.pyplot繪制一個更加詳細的散點組圖,這一次我們對上面散布圖矩陣中認為存在著一定線性相關的一些屬性,繪制為一個組圖,并要體現出這些線性相關是否與鳶尾花的子類別具有什么關系。
import pandas as pd import matplotlib.pyplot as pltfilename = 'iris_dataset/iris2.csv' dataset = pd.read_csv(filename)# for循環聲明一個子圖對象隊列 fig = plt.figure() ax = [] for i in range(1, 5):ax.append(plt.subplot(2, 2, i)) # 散點圖組圖 labels = ['Sepal.Length', 'Sepal.Width', 'Petal.Length', 'Petal.Width'] dataset.plot(x=labels[0], y=labels[2], kind='scatter', marker='x', ax=ax[0], c='Species', colormap='viridis') dataset.plot(x=labels[0], y=labels[3], kind='scatter', marker='x', ax=ax[1], c='Species') dataset.plot(x=labels[3], y=labels[1], kind='scatter', marker='x', ax=ax[2], c='Species') dataset.plot(x=labels[2], y=labels[3], kind='scatter', marker='x', ax=ax[3], c='Species')從這張更為細致的圖里,可以證實前面的推斷,鳶尾花依據其子類別屬性,在花瓣長度、花瓣寬度、花萼長度和花萼寬度之間有明確的線性關系,并且在其子類別versicolor和virginica中,這種線性關系更加明顯。
使用seaborn繪制散點圖,
聯合圖
#聯合分布圖函數原型聲明 #seaborn.jointplot(x, y, data=None, kind=’scatter’, stat_func=, color=None, size=6, ratio=5, space=0.2, dropna=True, xlim=None, ylim=None, joint_kws=None, marginal_kws=None, annot_kws=None, **kwargs) #hue:基于某列的類別將y分成不同顏色的點 sns.jointplot(x='Sepal.Length', y='Sepal.Width', hue='Species', data=dataset, kind='scatter')聯合分布圖不僅能看到數據屬性之間的相關性,也能看到對于某個類別的某個屬性值是如何分布的。
總結
以上是生活随笔為你收集整理的数据可视化(箱线图、直方图、散点图、联合分布图)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何将markdown文件转成word
- 下一篇: 市场调研报告-全球与中国数字钥匙模块市场