日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

数据可视化(箱线图、直方图、散点图、联合分布图)

發布時間:2024/1/8 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 数据可视化(箱线图、直方图、散点图、联合分布图) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

數據可視化

箱線圖可視化

箱線圖(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,

boxplot( x, notch=None, sym=None, vert=None, whis=None, positions=None, widths=None, patch_artist=None, bootstrap=None, usermedians=None, conf_intervals=None, meanline=None, showmeans=None, showcaps=None, showbox=None, showfliers=None, boxprops=None, labels=None, flierprops=None, medianprops=None, meanprops=None, capprops=None, whiskerprops=None, manage_ticks=True, autorange=False, zorder=None, *, data=None):x:指定要繪制箱線圖的數據,可以是一組數據也可以是多組數據; notch:是否以凹口的形式展現箱線圖,默認非凹口; sym:指定異常點的形狀,默認為藍色的+號顯示; vert:是否需要將箱線圖垂直擺放,默認垂直擺放; whis:指定上下須與上下四分位的距離,默認為1.5倍的四分位差; positions:指定箱線圖的位置,默認為range(1, N+1),N為箱線圖的數量; widths:指定箱線圖的寬度,默認為0.5; patch_artist:是否填充箱體的顏色,默認為False; meanline:是否用線的形式表示均值,默認用點來表示; showmeans:是否顯示均值,默認不顯示; showcaps:是否顯示箱線圖頂端和末端的兩條線,默認顯示; showbox:是否顯示箱線圖的箱體,默認顯示; showfliers:是否顯示異常值,默認顯示; boxprops:設置箱體的屬性,如邊框色,填充色等; labels:為箱線圖添加標簽,類似于圖例的作用; flierprops:設置異常值的屬性,如異常點的形狀、大小、填充色等; medianprops:設置中位數的屬性,如線的類型、粗細等; meanprops:設置均值的屬性,如點的大小、顏色等; capprops:設置箱線圖頂端和末端線條的屬性,如顏色、粗細等; whiskerprops:設置須的屬性,如顏色、粗細、線的類型等; manage_ticks:是否自適應標簽位置,默認為True; autorange:是否自動調整范圍,默認為False;

使用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
第三個,對參數有較為詳細的解釋。

import numpy as np import pandas as pd import matplotlib.pyplot as pltfilename = 'iris_dataset/iris.csv' dataset = pd.read_csv(filename) # 根據箱線圖繪制的思想,很容易想到可以用Pandas.DataFrame的對象的plot方法來繪制直方圖。 dataset.iloc[:, 1:5].plot(kind='hist') # 這里可以應用一個bins參數來控制圖畫的細致程度 plt.show()

上述這段代碼是利用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取值為序列,則該序列給出每個柱子的范圍值(即邊緣)。除最后一個柱子外,其他柱子的取值范圍均為半開(左閉右開)。

# 單屬性直方圖組圖 import pandas as pd import matplotlib.pyplot as pltfilename = 'iris_dataset/iris.csv' dataset = pd.read_csv(filename) labels = ['Sepal.Length', 'Sepal.Width', 'Petal.Length', 'Petal.Width'] colorDic = ['blue', 'orange', 'green', 'red']fig = plt.figure() for i in range(0, 4):ax = plt.subplot(2, 2, i+1)ax.hist(dataset[labels[i]], color=colorDic[i], label=labels[i])plt.legend() # 圖例說明 plt.show()

這里我特意貼出了畫在一起的直方圖和單屬性直方圖組圖。如果想仔細分析單個屬性,還是單屬性直方圖更為恰當?在第一張直方圖的繪制中,可以看到有一些屬性的圖像是被另一屬性的圖像覆蓋了一部分。這樣有什么意義呢?分類算法特征分析:我們可以看到花瓣長度在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繪制散點圖,

import pandas as pd import seaborn as sns import matplotlib.pyplot as pltfilename = 'iris_dataset/iris.csv' dataset = pd.read_csv(filename)fig = plt.figure() ax = [] for i in range(1, 5):ax.append(fig.add_subplot(2, 2, i))# sns.jointplot(x='Sepal.Length', y='Sepal.Width', hue='Species', data=dataset, kind='scatter', ax=ax1) sns.set(font_scale=1.2) sns.scatterplot(x='Sepal.Length', y='Petal.Length', hue='Species', data=dataset, ax=ax[0], marker='x') sns.scatterplot(x='Sepal.Length', y='Petal.Width', hue='Species', data=dataset, ax=ax[1], marker='x') sns.scatterplot(x='Petal.Width', y='Sepal.Width', hue='Species', data=dataset, ax=ax[2], marker='x') sns.scatterplot(x='Petal.Length', y='Petal.Width', hue='Species', data=dataset, ax=ax[3], marker='x')ax[0].legend(bbox_to_anchor=(2.5, 1.3), loc='best', frameon=False) ax[1].legend_.remove() ax[2].legend_.remove() ax[3].legend_.remove() plt.show()

聯合圖

#聯合分布圖函數原型聲明 #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')

聯合分布圖不僅能看到數據屬性之間的相關性,也能看到對于某個類別的某個屬性值是如何分布的。

總結

以上是生活随笔為你收集整理的数据可视化(箱线图、直方图、散点图、联合分布图)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。

主站蜘蛛池模板: 91黄免费| 国产一级免费大片 | 秋霞一区二区三区 | 国产精品视频一区二区三区 | 自拍偷拍av | 一级黄色片国产 | 香蕉视频久久久 | 50一60岁老妇女毛片 | 免费观看av的网站 | 91国产免费视频 | 欧美大片黄色 | 国产av一区二区三区精品 | aaaaaaa毛片| 亚洲第一免费 | 欧美乱妇日本无乱码特黄大片 | 呦女精品 | 国产欧美一区二区三区精品酒店 | 成人在线播放视频 | 91福利免费视频 | 成年人免费视频观看 | 一区二区视频观看 | 国产精品蜜 | 人乳喂奶hd无中字 | 亚洲是色 | 成人国产精品免费 | 五月婷婷六月香 | 欧美操大逼 | 91们嫩草伦理 | 加勒比综合网 | 欧美激情欧美激情在线五月 | 97超碰人人看| 黄色av三级 | 欧美日韩制服 | 97在线免费公开视频 | 国产crm系统91在线 | 91精品视频在线播放 | 亚洲不卡av一区二区 | 巨胸爆乳美女露双奶头挤奶 | 国产精品美乳在线观看 | 无码人妻丰满熟妇区五十路 | 啪啪小视频网站 | 日本一区二区高清免费 | 国产精品一区二区视频 | 亚洲精久久 | 国产免费一区二区三区 | 国产又粗又猛又爽又黄的视频小说 | 91麻豆产精品久久久久久夏晴子 | 嫩草网站在线观看 | 成人毛片18女人毛片免费 | 欧美天天影院 | 久久免费看少妇高潮v片特黄 | 99色亚洲 | 国产精品二 | 黄频在线 | 蜜臀av性久久久久蜜臀aⅴ流畅 | 黑人粗进入欧美aaaaa | 天天综合网久久综合网 | 性做久久| 麻豆久久久久久久久久 | www99热| 涩涩视频在线观看免费 | 成人区人妻精品一区 | 亚欧在线播放 | 久草视频在线资源 | 青青草国产成人99久久 | аⅴ资源中文在线天堂 | 伊人久久精品一区二区三区 | 久久六 | 影音先锋黄色资源 | 草久视频在线观看 | 国产一级做a爱免费视频 | 国产在线麻豆 | 国产麻豆一区二区三区在线观看 | 美女福利网站 | 成人无码精品1区2区3区免费看 | 三级欧美视频 | 桃花色综合影院 | 又粗又大又硬又长又爽 | 亚洲女优在线 | 狠狠艹视频 | 亚洲精品另类 | 久久精品无码毛片 | 熟女熟妇伦久久影院毛片一区二区 | 国产香蕉尹人视频在线 | 草1024榴社区成人 | 亚洲老妇色熟女老太 | 怡红院一区 | 日韩不卡一二区 | 华人永久免费 | www.夜夜骑 | www.欧美在线观看 | 亚洲精品911 | 日韩成人精品在线 | 国产视频手机在线播放 | 午夜激情视频 | 特级黄色网 | 古装三级吃奶做爰 | 尤物国产在线 | 成人激情社区 |