Python使用Seaborn快速生成高顏值業(yè)務(wù)圖表
本節(jié)學(xué)習(xí)目標(biāo)
完成本節(jié)學(xué)習(xí)后,你將能夠:
- 理解 Seaborn 與 Matplotlib 的關(guān)系和差異
- 使用 Seaborn 主題系統(tǒng)快速美化圖表
- 繪制各類分布圖(直方圖、KDE、箱線圖、小提琴圖)
- 繪制分類數(shù)據(jù)對(duì)比圖(條形圖、點(diǎn)圖、計(jì)數(shù)圖)
- 繪制回歸圖分析變量間關(guān)系
- 使用配對(duì)圖(pairplot)快速探索多變量關(guān)系
- 繪制熱力圖展示相關(guān)性矩陣和交叉數(shù)據(jù)
- 根據(jù)業(yè)務(wù)場(chǎng)景選擇合適的圖表類型
為什么學(xué)這個(gè)
想象一下這個(gè)場(chǎng)景:你花費(fèi)整整一個(gè)下午,用 Matplotlib 寫了 80 行代碼,調(diào)整了顏色、字體、間距、圖例位置……終于畫出了一張"勉強(qiáng)能看"的柱狀圖。然后你的同事用 Seaborn 寫了 3 行代碼,畫出了一張"驚艷全場(chǎng)"的圖表。老板夸贊同事:“這圖表做得真專業(yè)!”
這就是 Seaborn 的魅力——讓好看得毫不費(fèi)力。
Seaborn 是基于 Matplotlib 的高級(jí)可視化庫。它在 Matplotlib 的基礎(chǔ)上做了三件事:
- 內(nèi)置美觀的主題:默認(rèn)就好看,不需要反復(fù)調(diào)整
- 與 Pandas 深度集成:直接傳入 DataFrame,自動(dòng)識(shí)別列名
- 封裝統(tǒng)計(jì)功能:一鍵繪制帶統(tǒng)計(jì)信息的圖表(如回歸線、置信區(qū)間)
打個(gè)比方:如果說 Matplotlib 是"手動(dòng)擋汽車",你需要自己控制離合、換擋、油門;那么 Seaborn 就是"自動(dòng)擋汽車",你只需要告訴它目的地(數(shù)據(jù)),它自動(dòng)幫你選擇最佳路線。
核心知識(shí)點(diǎn)講解
一、Seaborn 主題設(shè)置與風(fēng)格美化
Seaborn 提供了 5 種內(nèi)置主題和多種調(diào)色板,這是它"開箱即美"的秘訣。
1.1 五大內(nèi)置主題
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
# Seaborn 五大主題:'darkgrid', 'whitegrid', 'dark', 'white', 'ticks'
themes = ['darkgrid', 'whitegrid', 'dark', 'white', 'ticks']
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
axes = axes.flatten()
x = np.linspace(0, 10, 100)
y = np.sin(x) + np.random.normal(0, 0.1, 100)
for i, theme in enumerate(themes):
sns.set_theme(style=theme)
axes[i].plot(x, y, linewidth=2)
axes[i].set_title(f"主題: {theme}", fontsize=13, fontweight='bold')
# 隱藏多余的子圖
axes[5].axis('off')
fig.suptitle('Seaborn 五大主題對(duì)比', fontsize=18, fontweight='bold', y=1.02)
plt.tight_layout()
plt.show()
主題選擇建議:
darkgrid:默認(rèn)主題,灰色網(wǎng)格,適合大多數(shù)場(chǎng)景whitegrid:白色背景加網(wǎng)格,適合學(xué)術(shù)論文dark:深色背景,適合大屏展示white:純白背景,適合印刷ticks:帶刻度線的簡(jiǎn)潔風(fēng)格
1.2 調(diào)色板(Palette)
調(diào)色板決定了圖表的顏色方案。Seaborn 提供三種調(diào)色板類型:
import seaborn as sns
import matplotlib.pyplot as plt
# 查看 Seaborn 內(nèi)置的所有調(diào)色板
palettes = ['deep', 'muted', 'pastel', 'bright', 'dark', 'colorblind']
fig, axes = plt.subplots(2, 3, figsize=(15, 6))
axes = axes.flatten()
for i, palette in enumerate(palettes):
colors = sns.color_palette(palette, 6)
sns.set_theme(style='white')
sns.barplot(x=['A', 'B', 'C', 'D', 'E', 'F'],
y=[30, 50, 40, 60, 35, 55],
palette=palette, ax=axes[i])
axes[i].set_title(f'調(diào)色板: {palette}', fontsize=12)
axes[i].set_xlabel('')
plt.tight_layout()
plt.show()
調(diào)色板選擇指南:
| 調(diào)色板 | 適用場(chǎng)景 | 特點(diǎn) |
|---|---|---|
deep | 通用 | 默認(rèn)配色,飽和度適中 |
muted | 學(xué)術(shù)報(bào)告 | 柔和不刺眼 |
pastel | 輕松場(chǎng)景 | 淡雅柔和 |
colorblind | 公共展示 | 色盲友好 |
Set1 / Set2 | 分類數(shù)據(jù) | 定性調(diào)色板 |
二、分布圖——理解數(shù)據(jù)的"長(zhǎng)相"
分布圖幫助我們回答:“數(shù)據(jù)集中在哪里?有沒有異常?對(duì)稱嗎?”
2.1 直方圖 + KDE 曲線(histplot)
直方圖展示數(shù)據(jù)分布,KDE(核密度估計(jì))是直方圖的"平滑版"。
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# 模擬數(shù)據(jù):?jiǎn)T工薪資分布
np.random.seed(42)
salaries = np.concatenate([
np.random.normal(8000, 1500, 200), # 普通員工
np.random.normal(15000, 3000, 50), # 中層管理
np.random.normal(30000, 5000, 10) # 高管
])
df = pd.DataFrame({'salary': salaries,
'level': ['普通員工']*200 + ['中層管理']*50 + ['高管']*10})
fig, axes = plt.subplots(1, 3, figsize=(18, 5))
# 子圖1:基礎(chǔ)直方圖
sns.histplot(data=df, x='salary', bins=30, kde=False,
color='#1E88E5', ax=axes[0])
axes[0].set_title('基礎(chǔ)直方圖', fontsize=14, fontweight='bold')
axes[0].set_xlabel('薪資(元)')
# 子圖2:直方圖 + KDE
sns.histplot(data=df, x='salary', bins=30, kde=True,
color='#E53935', ax=axes[1])
axes[1].set_title('直方圖 + KDE 密度曲線', fontsize=14, fontweight='bold')
axes[1].set_xlabel('薪資(元)')
# 子圖3:按類別分組的 KDE
sns.kdeplot(data=df, x='salary', hue='level', fill=True,
palette=['#4CAF50', '#FF9800', '#E53935'], ax=axes[2])
axes[2].set_title('按級(jí)別分組的薪資分布', fontsize=14, fontweight='bold')
axes[2].set_xlabel('薪資(元)')
plt.tight_layout()
plt.show()
2.2 箱線圖(boxplot)
箱線圖就像數(shù)據(jù)的"體檢報(bào)告",一眼看出中位數(shù)、四分位數(shù)和異常值。
最小值(非異常) 最大值(非異常)
| |
|--- 上須 ---| |--- 上須 ---|
| |
異常值 o | | o 異常值
┌─┐
──────────────┤ │├──────────────
Q1(25%) │ ││ Q3(75%)
└─┘
中位數(shù)
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# 模擬數(shù)據(jù):各部門薪資
np.random.seed(42)
df = pd.DataFrame({
'部門': np.random.choice(['技術(shù)部', '銷售部', '市場(chǎng)部', '運(yùn)營(yíng)部'], 200),
'薪資': np.random.normal(12000, 3000, 200) +
np.random.choice([2000, -1000, 500, -500], 200)
})
fig, axes = plt.subplots(1, 2, figsize=(14, 6))
# 子圖1:箱線圖
sns.boxplot(data=df, x='部門', y='薪資',
palette='Set2', ax=axes[0],
boxprops=dict(alpha=0.8),
flierprops=dict(marker='o', color='#E53935', alpha=0.5))
axes[0].set_title('各部門薪資箱線圖', fontsize=14, fontweight='bold')
axes[0].set_ylabel('薪資(元)')
# 子圖2:小提琴圖(箱線圖的"升級(jí)版",顯示分布密度)
sns.violinplot(data=df, x='部門', y='薪資',
palette='Set2', ax=axes[1],
inner='box') # inner='box' 在小提琴內(nèi)部畫箱線圖
axes[1].set_title('各部門薪資小提琴圖', fontsize=14, fontweight='bold')
axes[1].set_ylabel('薪資(元)')
plt.tight_layout()
plt.show()
三、分類圖——比較不同類別的數(shù)據(jù)
3.1 條形圖(barplot)
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# 模擬數(shù)據(jù):不同產(chǎn)品的季度銷售
np.random.seed(42)
df = pd.DataFrame({
'產(chǎn)品': np.random.choice(['產(chǎn)品A', '產(chǎn)品B', '產(chǎn)品C', '產(chǎn)品D'], 100),
'季度': np.random.choice(['Q1', 'Q2', 'Q3', 'Q4'], 100),
'銷量': np.random.randint(50, 200, 100)
})
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
# 子圖1:簡(jiǎn)單條形圖(自動(dòng)計(jì)算均值和置信區(qū)間)
sns.barplot(data=df, x='產(chǎn)品', y='銷量', palette='Set1', ax=axes[0])
axes[0].set_title('各產(chǎn)品平均銷量', fontsize=14, fontweight='bold')
axes[0].set_ylabel('平均銷量')
# 子圖2:分組條形圖
sns.barplot(data=df, x='產(chǎn)品', y='銷量', hue='季度', palette='viridis', ax=axes[1])
axes[1].set_title('各產(chǎn)品分季度銷量', fontsize=14, fontweight='bold')
axes[1].set_ylabel('平均銷量')
plt.tight_layout()
plt.show()
3.2 點(diǎn)圖(pointplot)
點(diǎn)圖強(qiáng)調(diào)數(shù)據(jù)點(diǎn)之間的趨勢(shì)變化,特別適合看"走勢(shì)"。
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# 模擬數(shù)據(jù):各渠道月度轉(zhuǎn)化率
np.random.seed(42)
df = pd.DataFrame({
'渠道': np.random.choice(['搜索', '社交', '郵件', '直訪'], 120),
'月份': np.tile(np.arange(1, 11), 12),
'轉(zhuǎn)化率': np.random.uniform(2, 8, 120) +
np.random.choice([1, 0, -0.5], 120)
})
fig, ax = plt.subplots(figsize=(10, 6))
sns.pointplot(data=df, x='月份', y='轉(zhuǎn)化率', hue='渠道',
palette='Set1', ax=ax,
marker='o', markersize=8,
errorbar='sd') # 誤差線使用標(biāo)準(zhǔn)差
ax.set_title('各渠道月度轉(zhuǎn)化率趨勢(shì)', fontsize=16, fontweight='bold')
ax.set_ylabel('轉(zhuǎn)化率(%)')
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
3.3 計(jì)數(shù)圖(countplot)
計(jì)數(shù)圖就是"數(shù)一數(shù)每個(gè)類別有多少條數(shù)據(jù)",相當(dāng)于分類的直方圖。
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# 模擬數(shù)據(jù):客戶滿意度調(diào)查
np.random.seed(42)
df = pd.DataFrame({
'滿意度': np.random.choice(['非常不滿意', '不滿意', '一般', '滿意', '非常滿意'],
200, p=[0.05, 0.15, 0.30, 0.35, 0.15]),
'渠道': np.random.choice(['線上', '線下'], 200)
})
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
# 子圖1:簡(jiǎn)單計(jì)數(shù)圖
sns.countplot(data=df, x='滿意度', palette='RdYlGn', order=['非常不滿意', '不滿意', '一般', '滿意', '非常滿意'], ax=axes[0])
axes[0].set_title('客戶滿意度分布', fontsize=14, fontweight='bold')
axes[0].tick_params(axis='x', rotation=30)
# 子圖2:分組計(jì)數(shù)圖
sns.countplot(data=df, x='滿意度', hue='渠道', palette='Set2',
order=['非常不滿意', '不滿意', '一般', '滿意', '非常滿意'], ax=axes[1])
axes[1].set_title('各渠道客戶滿意度分布', fontsize=14, fontweight='bold')
axes[1].tick_params(axis='x', rotation=30)
plt.tight_layout()
plt.show()
四、回歸圖——分析變量之間的關(guān)系
回歸圖不僅能展示兩個(gè)變量的關(guān)系,還會(huì)自動(dòng)擬合回歸線并顯示置信區(qū)間。
4.1 散點(diǎn)回歸圖(regplot)
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# 模擬數(shù)據(jù):廣告投入與銷售額
np.random.seed(42)
n = 100
df = pd.DataFrame({
'廣告投入': np.random.uniform(5, 50, n),
'銷售額': 0,
'渠道': np.random.choice(['線上', '線下', '社交'], n)
})
# 銷售額 = 2.5 * 廣告投入 + 隨機(jī)噪聲 + 渠道效應(yīng)
df['銷售額'] = (2.5 * df['廣告投入'] +
np.random.normal(0, 10, n) +
np.where(df['渠道'] == '線上', 20,
np.where(df['渠道'] == '社交', 10, 0)))
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
# 子圖1:整體回歸圖
sns.regplot(data=df, x='廣告投入', y='銷售額',
scatter_kws={'alpha': 0.6, 's': 60},
line_kws={'color': '#E53935', 'linewidth': 2},
ax=axes[0])
axes[0].set_title('廣告投入與銷售額(整體回歸)', fontsize=13, fontweight='bold')
# 子圖2:按渠道分組的回歸圖(lmplot 風(fēng)格)
for channel, color in zip(['線上', '線下', '社交'], ['#1E88E5', '#43A047', '#FB8C00']):
subset = df[df['渠道'] == channel]
sns.regplot(data=subset, x='廣告投入', y='銷售額',
scatter_kws={'alpha': 0.6, 's': 50},
line_kws={'color': color, 'linewidth': 2},
ax=axes[1], label=channel)
axes[1].set_title('分渠道回歸分析', fontsize=13, fontweight='bold')
axes[1].legend()
plt.tight_layout()
plt.show()
五、配對(duì)圖(pairplot)——多變量關(guān)系的"全景圖"
pairplot 是 EDA(探索性數(shù)據(jù)分析)中最強(qiáng)大的工具之一。它一次性展示所有數(shù)值變量?jī)蓛芍g的關(guān)系。
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# 使用內(nèi)置的 iris 數(shù)據(jù)集(如果無法加載,使用模擬數(shù)據(jù))
try:
iris = sns.load_dataset('iris')
except:
np.random.seed(42)
iris = pd.DataFrame({
'sepal_length': np.concatenate([np.random.normal(5.0, 0.35, 50),
np.random.normal(5.9, 0.5, 50),
np.random.normal(6.6, 0.6, 50)]),
'sepal_width': np.concatenate([np.random.normal(3.4, 0.38, 50),
np.random.normal(2.8, 0.3, 50),
np.random.normal(3.0, 0.35, 50)]),
'petal_length': np.concatenate([np.random.normal(1.5, 0.17, 50),
np.random.normal(4.3, 0.47, 50),
np.random.normal(5.6, 0.55, 50)]),
'petal_width': np.concatenate([np.random.normal(0.25, 0.1, 50),
np.random.normal(1.3, 0.2, 50),
np.random.normal(2.0, 0.27, 50)]),
'species': ['setosa']*50 + ['versicolor']*50 + ['virginica']*50
})
# 創(chuàng)建配對(duì)圖
g = sns.pairplot(iris, hue='species', palette='Set1',
diag_kind='kde', # 對(duì)角線用 KDE 圖
markers=['o', 's', 'D'],
plot_kws={'alpha': 0.7, 's': 80})
g.fig.suptitle('鳶尾花數(shù)據(jù)集配對(duì)圖', fontsize=18, fontweight='bold', y=1.02)
plt.show()
pairplot 解讀技巧:
- 對(duì)角線:每個(gè)變量自身的分布(直方圖或 KDE)
- 下三角/上三角:兩兩變量之間的散點(diǎn)圖
- 顏色:按類別分組,觀察不同類別是否聚集
六、熱力圖(heatmap)——矩陣數(shù)據(jù)的"可視化放大鏡"
熱力圖用顏色深淺表示數(shù)值大小,是展示相關(guān)性矩陣、交叉分析表的利器。
6.1 相關(guān)性熱力圖
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# 模擬數(shù)據(jù):業(yè)務(wù)指標(biāo)相關(guān)性分析
np.random.seed(42)
df = pd.DataFrame({
'廣告投入': np.random.uniform(10, 100, 200),
'網(wǎng)站流量': 0,
'注冊(cè)人數(shù)': 0,
'購買人數(shù)': 0,
'客單價(jià)': 0,
'總營(yíng)收': 0
})
# 生成有相關(guān)性的數(shù)據(jù)
df['網(wǎng)站流量'] = df['廣告投入'] * 3 + np.random.normal(0, 50, 200)
df['注冊(cè)人數(shù)'] = df['網(wǎng)站流量'] * 0.1 + np.random.normal(0, 20, 200)
df['購買人數(shù)'] = df['注冊(cè)人數(shù)'] * 0.3 + np.random.normal(0, 10, 200)
df['客單價(jià)'] = np.random.normal(200, 50, 200)
df['總營(yíng)收'] = df['購買人數(shù)'] * df['客單價(jià)'] + np.random.normal(0, 5000, 200)
# 計(jì)算相關(guān)系數(shù)矩陣
corr_matrix = df.corr()
fig, axes = plt.subplots(1, 2, figsize=(16, 6))
# 子圖1:完整熱力圖
sns.heatmap(corr_matrix, annot=True, cmap='coolwarm', center=0,
fmt='.2f', linewidths=0.5, ax=axes[0],
cbar_kws={'label': '相關(guān)系數(shù)'})
axes[0].set_title('業(yè)務(wù)指標(biāo)相關(guān)性熱力圖', fontsize=14, fontweight='bold')
# 子圖2:上三角掩碼(只看一半)
mask = np.triu(np.ones_like(corr_matrix, dtype=bool))
sns.heatmap(corr_matrix, annot=True, cmap='coolwarm', center=0,
mask=mask, fmt='.2f', linewidths=0.5, ax=axes[1],
cbar_kws={'label': '相關(guān)系數(shù)'})
axes[1].set_title('上三角掩碼熱力圖(去重)', fontsize=14, fontweight='bold')
plt.tight_layout()
plt.show()
6.2 聚類熱力圖(clustermap)
clustermap 會(huì)自動(dòng)對(duì)行和列進(jìn)行聚類,把相似的數(shù)據(jù)聚在一起。
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# 模擬數(shù)據(jù):不同城市各月銷售額
np.random.seed(42)
cities = ['北京', '上海', '廣州', '深圳', '杭州', '成都', '南京', '武漢']
months = [f'{i}月' for i in range(1, 13)]
# 生成有季節(jié)性的數(shù)據(jù)
data = {}
for city in cities:
base = np.random.uniform(100, 300)
seasonal = 30 * np.sin(np.linspace(0, 2*np.pi, 12))
data[city] = base + seasonal + np.random.normal(0, 15, 12)
df = pd.DataFrame(data, index=months)
# 繪制聚類熱力圖
g = sns.clustermap(df.T, cmap='YlOrRd', figsize=(12, 8),
annot=True, fmt='.0f', linewidths=0.5,
cbar_kws={'label': '銷售額(萬元)'})
g.fig.suptitle('各城市月度銷售聚類熱力圖', fontsize=16, fontweight='bold', y=1.02)
plt.show()
七、Seaborn 高級(jí)技巧
7.1 自定義主題參數(shù)
import seaborn as sns
import matplotlib.pyplot as plt
# 使用 set_theme 自定義主題
sns.set_theme(
style='darkgrid', # 背景風(fēng)格
palette='Set2', # 默認(rèn)調(diào)色板
font='sans-serif', # 字體
font_scale=1.2, # 字體縮放比例
rc={ # matplotlib 參數(shù)
'axes.titlesize': 16,
'axes.titleweight': 'bold',
'axes.labelsize': 13,
'legend.fontsize': 11,
'figure.titlesize': 18
}
)
# 之后所有圖表都會(huì)使用這個(gè)主題
fig, ax = plt.subplots(figsize=(10, 6))
tips = sns.load_dataset('tips')
sns.boxplot(data=tips, x='day', y='total_bill', hue='sex', ax=ax)
ax.set_title('自定義主題后的圖表', fontsize=18)
plt.tight_layout()
plt.show()
7.2 FacetGrid——分面圖
FacetGrid 允許你按照某個(gè)分類變量將數(shù)據(jù)分成多個(gè)子圖,每個(gè)子圖展示一個(gè)子集。
import seaborn as sns
import matplotlib.pyplot as plt
# 使用內(nèi)置數(shù)據(jù)集
tips = sns.load_dataset('tips')
# 按「時(shí)間」和「吸煙」分面
g = sns.FacetGrid(tips, col='time', row='smoker', height=4, aspect=1.2)
g.map(sns.scatterplot, 'total_bill', 'tip', alpha=0.7, s=80)
g.add_legend()
g.fig.suptitle('小費(fèi)數(shù)據(jù)集分面圖', fontsize=16, fontweight='bold', y=1.02)
plt.tight_layout()
plt.show()
實(shí)戰(zhàn)練習(xí)
練習(xí)一:電商用戶行為分析
假設(shè)你有一份電商用戶行為數(shù)據(jù),包含用戶ID、訪問頁面數(shù)、停留時(shí)長(zhǎng)、購買金額、用戶等級(jí)。請(qǐng)完成以下分析:
- 繪制購買金額的分布圖(直方圖+KDE)
- 按用戶等級(jí)繪制購買金額的箱線圖
- 繪制訪問頁面數(shù)與購買金額的關(guān)系圖(含回歸線)
- 繪制各指標(biāo)的相關(guān)性熱力圖
參考答案:
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# 生成模擬數(shù)據(jù)
np.random.seed(42)
n = 500
df = pd.DataFrame({
'用戶ID': range(1, n+1),
'訪問頁面數(shù)': np.random.randint(1, 20, n),
'停留時(shí)長(zhǎng)': np.random.exponential(15, n),
'購買金額': 0,
'用戶等級(jí)': np.random.choice(['青銅', '白銀', '黃金', '鉆石'], n, p=[0.4, 0.3, 0.2, 0.1])
})
# 購買金額與等級(jí)和頁面數(shù)相關(guān)
grade_bonus = {'青銅': 0, '白銀': 50, '黃金': 100, '鉆石': 200}
df['購買金額'] = (df['訪問頁面數(shù)'] * 15 +
df['停留時(shí)長(zhǎng)'] * 5 +
df['用戶等級(jí)'].map(grade_bonus) +
np.random.normal(0, 50, n))
df['購買金額'] = df['購買金額'].clip(0)
# 設(shè)置主題
sns.set_theme(style='whitegrid', font_scale=1.1)
fig = plt.figure(figsize=(18, 12))
fig.suptitle('電商用戶行為分析報(bào)告', fontsize=20, fontweight='bold', y=0.98)
# 1. 購買金額分布
ax1 = fig.add_subplot(2, 2, 1)
sns.histplot(data=df, x='購買金額', kde=True, bins=30, color='#1E88E5', ax=ax1)
ax1.set_title('購買金額分布', fontsize=14)
# 2. 按等級(jí)的箱線圖
ax2 = fig.add_subplot(2, 2, 2)
grade_order = ['青銅', '白銀', '黃金', '鉆石']
sns.boxplot(data=df, x='用戶等級(jí)', y='購買金額', order=grade_order,
palette='Set1', ax=ax2)
ax2.set_title('各等級(jí)用戶購買金額對(duì)比', fontsize=14)
# 3. 回歸圖
ax3 = fig.add_subplot(2, 2, 3)
sns.regplot(data=df, x='訪問頁面數(shù)', y='購買金額',
scatter_kws={'alpha': 0.4, 's': 40},
line_kws={'color': '#E53935'}, ax=ax3)
ax3.set_title('頁面數(shù)與購買金額關(guān)系', fontsize=14)
# 4. 相關(guān)性熱力圖
ax4 = fig.add_subplot(2, 2, 4)
numeric_df = df[['訪問頁面數(shù)', '停留時(shí)長(zhǎng)', '購買金額']]
corr = numeric_df.corr()
sns.heatmap(corr, annot=True, cmap='coolwarm', center=0, fmt='.2f', ax=ax4)
ax4.set_title('數(shù)值指標(biāo)相關(guān)性', fontsize=14)
plt.tight_layout()
plt.show()
練習(xí)二:產(chǎn)品滿意度調(diào)查可視化
某公司對(duì)新產(chǎn)品進(jìn)行滿意度調(diào)查,收集了評(píng)分(1-5分)、使用時(shí)長(zhǎng)、年齡段、性別等數(shù)據(jù)。請(qǐng)用 Seaborn 繪制一份完整的分析報(bào)告。
參考答案:
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# 生成數(shù)據(jù)
np.random.seed(42)
n = 300
df = pd.DataFrame({
'評(píng)分': np.random.choice([1, 2, 3, 4, 5], n, p=[0.05, 0.1, 0.25, 0.4, 0.2]),
'使用時(shí)長(zhǎng)(月)': np.random.exponential(6, n),
'年齡段': np.random.choice(['18-25', '26-35', '36-45', '46+'], n, p=[0.3, 0.4, 0.2, 0.1]),
'性別': np.random.choice(['男', '女'], n)
})
# 設(shè)置主題
sns.set_theme(style='darkgrid', palette='Set2', font_scale=1.1)
fig, axes = plt.subplots(2, 2, figsize=(16, 12))
fig.suptitle('產(chǎn)品滿意度調(diào)查報(bào)告', fontsize=20, fontweight='bold', y=1.02)
# 1. 評(píng)分分布(計(jì)數(shù)圖)
sns.countplot(data=df, x='評(píng)分', palette='RdYlGn', ax=axes[0, 0])
axes[0, 0].set_title('評(píng)分分布', fontsize=14)
axes[0, 0].set_xlabel('評(píng)分')
# 2. 不同年齡段評(píng)分對(duì)比(小提琴圖)
age_order = ['18-25', '26-35', '36-45', '46+']
sns.violinplot(data=df, x='年齡段', y='評(píng)分', order=age_order,
palette='Set1', ax=axes[0, 1], inner='box')
axes[0, 1].set_title('年齡段與評(píng)分', fontsize=14)
# 3. 性別與使用時(shí)長(zhǎng)(分組箱線圖)
sns.boxplot(data=df, x='性別', y='使用時(shí)長(zhǎng)(月)', hue='性別',
palette='Set1', ax=axes[1, 0], legend=False)
axes[1, 0].set_title('不同性別使用時(shí)長(zhǎng)', fontsize=14)
# 4. 使用時(shí)長(zhǎng)與評(píng)分的關(guān)系(點(diǎn)圖)
sns.pointplot(data=df, x='評(píng)分', y='使用時(shí)長(zhǎng)(月)', ax=axes[1, 1],
palette='Set1', errorbar='sd')
axes[1, 1].set_title('評(píng)分與使用時(shí)長(zhǎng)的關(guān)系', fontsize=14)
plt.tight_layout()
plt.show()
本節(jié)總結(jié)
本節(jié)我們深入學(xué)習(xí)了 Seaborn 這個(gè)"高顏值"可視化工具:
- 主題系統(tǒng):5 種主題 + 多種調(diào)色板,讓圖表開箱即美
- 分布圖:histplot、kdeplot、boxplot、violinplot,全面掌握數(shù)據(jù)分布特征
- 分類圖:barplot、pointplot、countplot,擅長(zhǎng)比較不同類別
- 回歸圖:regplot 自動(dòng)擬合回歸線,快速探索變量關(guān)系
- 配對(duì)圖:pairplot 一張圖展示所有變量關(guān)系,EDA 利器
- 熱力圖:heatmap 和 clustermap,矩陣數(shù)據(jù)的可視化利器
- 分面圖:FacetGrid 按類別拆分?jǐn)?shù)據(jù),多維度對(duì)比
核心認(rèn)知:Seaborn 不是替代 Matplotlib,而是在它之上提供了更便捷的統(tǒng)計(jì)繪圖接口。當(dāng)你需要復(fù)雜定制時(shí),仍然可以回退到 Matplotlib 的 Axes 對(duì)象進(jìn)行操作。
以上就是Python使用Seaborn快速生成高顏值業(yè)務(wù)圖表的詳細(xì)內(nèi)容,更多關(guān)于Python Seaborn生成業(yè)務(wù)圖表的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python使用epoll實(shí)現(xiàn)服務(wù)端的方法
今天小編就為大家分享一篇python使用epoll實(shí)現(xiàn)服務(wù)端的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-10-10
Python將8位的圖片轉(zhuǎn)為24位的圖片實(shí)現(xiàn)方法
這篇文章主要介紹了Python將8位的圖片轉(zhuǎn)為24位的圖片的實(shí)現(xiàn)代碼,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-10-10
python實(shí)現(xiàn)圖片彩色轉(zhuǎn)化為素描
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)圖片彩色轉(zhuǎn)化為素描,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-01-01
解決python父線程關(guān)閉后子線程不關(guān)閉問題
這篇文章主要介紹了解決python父線程關(guān)閉后子線程不關(guān)閉問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-04-04
pandas數(shù)據(jù)合并之pd.concat()用法詳解
本文主要介紹了pandas數(shù)據(jù)合并之pd.concat()用法詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06
python創(chuàng)建Flask Talisman應(yīng)用程序的步驟詳解
Flask是一個(gè)功能強(qiáng)大的Web框架,主要用于使用Python語言開發(fā)有趣的Web應(yīng)用程序,Talisman基本上是一個(gè)Flask擴(kuò)展,用于添加HTTP安全標(biāo)頭我們的Flask應(yīng)用程序易于實(shí)施,本文就給大家講講帶Talisman的Flask安全性,需要的朋友可以參考下2023-09-09

