Python 可視化:Seaborn 庫使用基礎(chǔ)
大家好,我是了不起。
當使用Seaborn進行可視化分析時,你可以通過以下多個例子來展示Seaborn的各種屬性和功能。我將為你提供一些簡單到復雜的示例,并附上詳細的注釋和說明。

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
































