Python 數(shù)據(jù)科學(xué)中的 Seaborn 繪圖可視化

pip install seabornhttps://seaborn.pydata.org/
https://seaborn.pydata.org/api.html
Financial Sample.xlsx
import pandas as pdimport seaborn as sns#如果使用 Jupyter Notebooks,下面的行允許我們在瀏覽器中顯示圖表%matplotlib inline#在 Pandas DataFrame 中加載我們的數(shù)據(jù)df = pd.read_excel('Financial Sample.xlsx')#打印前 5 行數(shù)據(jù)以確保正確加載df.head()

#繪制 DataFrame "Profit" 列的分布sns.displot(df['Profit'])

#設(shè)置我們希望用于繪圖的樣式sns.set_style("darkgrid")#繪制 DataFrame "Profit" 列的分布sns.displot(df['Profit'])

“kde=False”,我們可以刪除 KDE。我們還可以按如下方式更改直方圖中“bins”的數(shù)量——在本例中,它們被設(shè)置為 50:sns.displot(df['Profit'],kde=False,bins=50)
“Profit”列與“Units Sold”列。sns.jointplot(x='Profit',y='Units Sold',data=df)
sns.jointplot(x='Profit',y='Units Sold',data=df,kind='hex')
“kind”添加的另一個參數(shù)是“reg”,它代表回歸。這看起來很像散點圖,但這次將添加線性回歸線。sns.jointplot(x='Profit',y='Units Sold',data=df,kind='reg')
“kde”,它將繪制一個二維 KDE 圖,它基本上只顯示數(shù)據(jù)點最常出現(xiàn)的位置的密度。sns.jointplot(x='Profit',y='Units Sold',data=df,kind='kde')
“pairplots”。這些使我們能夠查看整個數(shù)據(jù)幀(對于數(shù)值數(shù)據(jù))的成對關(guān)系,并且還支持分類數(shù)據(jù)點的“色調(diào)”參數(shù)。所以 pairplot 本質(zhì)上是為 DataFrame 中數(shù)字列的每個可能組合創(chuàng)建一個聯(lián)合圖。我將快速創(chuàng)建一個新的 DataFrame,它刪除“Month Number”和“Year”列,因為這些并不是我們連續(xù)數(shù)字?jǐn)?shù)據(jù)的一部分,例如“利潤”和“COGS”(銷售成本)。我還將刪除其他幾列以縮小我們的 DataFrame,這樣我們的輸出圖就不會過于擁擠。#刪除不需要的列new_df = df.drop(['Month Number','Year','Manufacturing Price','Sale Price'],axis=1)sns.pairplot(new_df)

sns.pairplot(new_df,hue='Segment')
sns.pairplot(new_df,hue='Segment',palette='magma')
“rugplot”——這將幫助我們構(gòu)建和解釋我們之前創(chuàng)建的“kde”圖是什么——無論是在我們的 distplot 中還是當(dāng)我們傳遞“kind=kde”作為我們的參數(shù)時。sns.rugplot(df['Profit'])
#設(shè)置一組 30 個取自正態(tài)分布的數(shù)據(jù)點x = np.random.normal(0, 1, size=30)#設(shè)置 KDE 點的帶寬bandwidth = 1.06* x.std() * x.size ** (-1/ 5.)#設(shè)置 y 軸的限制support = np.linspace(-4, 4, 200)#遍歷數(shù)據(jù)點并為每個點創(chuàng)建內(nèi)核,然后繪制內(nèi)核kernels = []for x_i in x:kernel = stats.norm(x_i, bandwidth).pdf(support)kernels.append(kernel)plt.plot(support, kernel, color="r")sns.rugplot(x, color=".2", linewidth=3)

#使用復(fù)合梯形規(guī)則沿給定軸積分并創(chuàng)建 KDE 圖from scipy.integrate import trapzdensity = np.sum(kernels, axis=0)density /= trapz(density, support)plt.plot(support, density)

“kdeplot”繪制 KDE 圖。sns.kdeplot(x, shade=True)
評論
圖片
表情
