Python 可視化:Seaborn 庫(kù)使用基礎(chǔ)
大家好,我是了不起。
當(dāng)使用Seaborn進(jìn)行可視化分析時(shí),你可以通過(guò)以下多個(gè)例子來(lái)展示Seaborn的各種屬性和功能。我將為你提供一些簡(jiǎn)單到復(fù)雜的示例,并附上詳細(xì)的注釋和說(shuō)明。
1. 簡(jiǎn)單的散點(diǎn)圖
首先,讓我們創(chuàng)建一個(gè)簡(jiǎn)單的散點(diǎn)圖,用Seaborn可視化數(shù)據(jù)集中的兩個(gè)變量。我們將使用Seaborn的scatterplot函數(shù)。
import seaborn as sns
import matplotlib.pyplot as plt
# 使用Seaborn內(nèi)置的數(shù)據(jù)集
tips = sns.load_dataset('tips')
# 創(chuàng)建散點(diǎn)圖
sns.scatterplot(x='total_bill', y='tip', data=tips)
# 添加標(biāo)題和標(biāo)簽
plt.title('Total Bill vs Tip')
plt.xlabel('Total Bill ($)')
plt.ylabel('Tip ($)')
# 顯示圖形
plt.show()
這個(gè)例子展示了如何使用Seaborn的scatterplot函數(shù)創(chuàng)建一個(gè)簡(jiǎn)單的散點(diǎn)圖,并自定義標(biāo)題和標(biāo)簽。
2. 柱狀圖與分組
接下來(lái),讓我們創(chuàng)建一個(gè)柱狀圖,展示不同性別的顧客在餐廳中的平均付款金額。
import seaborn as sns
import matplotlib.pyplot as plt
# 使用Seaborn內(nèi)置的數(shù)據(jù)集
tips = sns.load_dataset('tips')
# 創(chuàng)建柱狀圖
sns.barplot(x='sex', y='total_bill', data=tips, ci=None)
# 添加標(biāo)題和標(biāo)簽
plt.title('Average Total Bill by Gender')
plt.xlabel('Gender')
plt.ylabel('Average Total Bill ($)')
# 顯示圖形
plt.show()
在這個(gè)示例中,我們使用了barplot函數(shù)創(chuàng)建柱狀圖,并通過(guò)ci=None參數(shù)禁用了置信區(qū)間的顯示。
3. 箱線圖與分布
現(xiàn)在,讓我們創(chuàng)建一個(gè)箱線圖,同時(shí)顯示不同用餐時(shí)間的顧客總賬單分布。
import seaborn as sns
import matplotlib.pyplot as plt
# 使用Seaborn內(nèi)置的數(shù)據(jù)集
tips = sns.load_dataset('tips')
# 創(chuàng)建箱線圖
sns.boxplot(x='time', y='total_bill', data=tips)
# 添加標(biāo)題和標(biāo)簽
plt.title('Total Bill Distribution by Dining Time')
plt.xlabel('Dining Time')
plt.ylabel('Total Bill ($)')
# 顯示圖形
plt.show()
這個(gè)示例中,我們使用了boxplot函數(shù)創(chuàng)建箱線圖,展示了不同用餐時(shí)間下的總賬單分布情況。
4. 分類散點(diǎn)圖與回歸線
接下來(lái),讓我們創(chuàng)建一個(gè)分類散點(diǎn)圖,同時(shí)添加回歸線,以顯示顧客總賬單和小費(fèi)之間的關(guān)系。
import seaborn as sns
import matplotlib.pyplot as plt
# 使用Seaborn內(nèi)置的數(shù)據(jù)集
tips = sns.load_dataset('tips')
# 創(chuàng)建分類散點(diǎn)圖和回歸線
sns.lmplot(x='total_bill', y='tip', data=tips, hue='sex')
# 添加標(biāo)題和標(biāo)簽
plt.title('Total Bill vs Tip with Regression Line (Separated by Gender)')
plt.xlabel('Total Bill ($)')
plt.ylabel('Tip ($)')
# 顯示圖形
plt.show()
在這個(gè)示例中,我們使用lmplot函數(shù)創(chuàng)建了分類散點(diǎn)圖,并使用hue參數(shù)將數(shù)據(jù)按性別分組,并添加了回歸線。
5. 熱力圖
最后,讓我們創(chuàng)建一個(gè)熱力圖,展示不同變量之間的相關(guān)性。
import seaborn as sns
import matplotlib.pyplot as plt
# 使用Seaborn內(nèi)置的數(shù)據(jù)集
tips = sns.load_dataset('tips')
# 計(jì)算變量之間的相關(guān)性矩陣
correlation_matrix = tips.corr()
# 創(chuàng)建熱力圖
sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm')
# 添加標(biāo)題
plt.title('Correlation Heatmap')
# 顯示圖形
plt.show()
這個(gè)示例中,我們使用heatmap函數(shù)創(chuàng)建了一個(gè)熱力圖,用不同顏色表示不同變量之間的相關(guān)性,并使用annot=True在圖中顯示相關(guān)性值。
這些示例展示了Seaborn的不同屬性和功能,從簡(jiǎn)單的散點(diǎn)圖到復(fù)雜的熱力圖,你可以根據(jù)你的數(shù)據(jù)和需求選擇合適的Seaborn函數(shù)來(lái)創(chuàng)建可視化圖表。Seaborn提供了豐富的功能和美觀的默認(rèn)樣式,使數(shù)據(jù)可視化變得更加容易和具有吸引力。