找回密码
立即注册
搜索
热搜: Java Python Linux Go
发回帖 发新帖

2999

积分

0

好友

433

主题
发表于 8 小时前 | 查看: 1| 回复: 0

Python数据可视化进阶:掌握Seaborn高级图表与实战技巧

在数据科学领域,清晰直观的可视化是传达信息、发现洞察的关键。虽然Matplotlib功能强大,但在创建具有统计意义的复杂图表时往往需要大量代码。这时,基于Python和Matplotlib构建的Seaborn库便脱颖而出。本文将带你深入Seaborn的高级功能,通过丰富的代码示例,掌握从关系分析、分类比较到分布探索的全套可视化技能。

一、Seaborn简介与优势

Seaborn是一个专注于统计图形绘制的Python库。它简化了创建信息丰富且美观的可视化图表的过程。让我们先了解其基本用法和核心优势。

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

print(f"Seaborn版本: {sns.__version__}")

# Seaborn的三大优势
"""
1. 美观的默认样式和颜色主题
2. 高级统计图表,简化复杂可视化
3. 与Pandas数据结构完美集成
4. 内置复杂统计功能支持
"""

Seaborn的优势在于其高层抽象,它能用一两行代码生成在Matplotlib中需要大量定制才能完成的统计图表,并且其默认的美学设计足以满足多数出版级别的需求。

二、Seaborn基础与配置

良好的开始是成功的一半。在使用Seaborn绘图前,进行恰当的全局配置和了解其内置数据集,能让后续工作事半功倍。

# 1. Seaborn配置
# 设置全局样式和颜色主题
sns.set_theme(
    style="whitegrid",      # 样式:darkgrid, whitegrid, dark, white, ticks
    context="notebook",     # 上下文:paper, notebook, talk, poster
    palette="husl",         # 调色板:deep, muted, bright, pastel, dark, colorblind
    font="sans-serif",      # 字体
    font_scale=1.2,         # 字体缩放
    rc={                    # 自定义rc参数
        'figure.figsize': (10, 6),
        'axes.titlesize': 16,
        'axes.labelsize': 14
    }
)

# 2. 内置数据集加载
print("Seaborn内置数据集:")
print([dataset for dataset in dir(sns.datasets) if not dataset.startswith('_')])

# 加载示例数据集
titanic = sns.load_dataset('titanic')
tips = sns.load_dataset('tips')
iris = sns.load_dataset('iris')
penguins = sns.load_dataset('penguins')

print(f"\nTitanic数据形状: {titanic.shape}")
print(f"Tips数据形状: {tips.shape}")
print(f"Iris数据形状: {iris.shape}")

sns.set_theme() 是Seaborn的核心配置函数,它能一次性设置样式、调色板、字体大小等,让你的所有图表风格统一。而内置数据集则为我们学习和演示提供了极大的便利。

三、关系型数据可视化

探索变量之间的关系是数据分析的起点。Seaborn提供了一系列强大的工具来可视化这种关系,并附带了回归分析等功能。

1. 散点图与回归分析

散点图是展示两个连续变量关系的经典图表。Seaborn的 scatterplotregplot 在此基础上增加了分类、回归线等高级功能。

# 创建图形布局
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
fig.suptitle('Seaborn关系型可视化', fontsize=18, fontweight='bold')

# 1. 基本散点图
sns.scatterplot(
    data=tips,
    x='total_bill',
    y='tip',
    ax=axes[0, 0]
)
axes[0, 0].set_title('基本散点图')

# 2. 分类散点图(hue参数)
sns.scatterplot(
    data=tips,
    x='total_bill',
    y='tip',
    hue='sex',          # 按性别分类
    style='smoker',     # 按是否吸烟区分标记样式
    size='size',        # 按用餐人数设置标记大小
    sizes=(20, 200),    # 标记大小范围
    alpha=0.7,          # 透明度
    ax=axes[0, 1]
)
axes[0, 1].set_title('多维度散点图')
axes[0, 1].legend(loc='upper left', bbox_to_anchor=(1, 1))

# 3. 带回归线的散点图
sns.regplot(
    data=tips,
    x='total_bill',
    y='tip',
    scatter_kws={'alpha': 0.5, 'color': 'steelblue'},
    line_kws={'color': 'red', 'linewidth': 2},
    ax=axes[0, 2]
)
axes[0, 2].set_title('线性回归分析')

# 4. 核密度估计回归
sns.regplot(
    data=tips,
    x='total_bill',
    y='tip',
    lowess=True,        # 使用局部加权散点平滑
    scatter_kws={'alpha': 0.3},
    line_kws={'color': 'green', 'linewidth': 2},
    ax=axes[1, 0]
)
axes[1, 0].set_title('LOESS回归')

# 5. 残差图
sns.residplot(
    data=tips,
    x='total_bill',
    y='tip',
    lowess=True,
    scatter_kws={'alpha': 0.6},
    line_kws={'color': 'red'},
    ax=axes[1, 1]
)
axes[1, 1].set_title('回归残差图')

plt.tight_layout()
plt.show()

# 6. 联合分布图(JointPlot)
# 这个需要单独创建图形

# 创建联合分布图
g = sns.jointplot(
    data=tips,
    x='total_bill',
    y='tip',
    kind='reg',        # 类型:scatter, reg, resid, kde, hex, hist
    height=7,
    ratio=5,
    marginal_kws={'kde': True, 'fill': True},
    joint_kws={'scatter_kws': {'alpha': 0.5}}
)
g.plot_joint(sns.kdeplot, color='r', alpha=0.5, zorder=0, levels=5)
g.fig.suptitle('联合分布图:小费与账单金额', y=1.02, fontsize=16)
plt.tight_layout()
plt.show()

通过 hue, style, size 参数,单张散点图可以同时编码四个维度的信息,这是传统散点图难以实现的。而 jointplot 更是将双变量关系与各自的边缘分布完美结合。

2. 多变量关系分析

当需要同时探索多个数值变量之间的所有两两关系时,成对关系图(PairPlot)是最佳选择。

# 成对关系图(PairPlot)
print("创建鸢尾花数据集成对关系图...")
iris_pair = sns.pairplot(
    data=iris,
    hue='species',           # 按物种分类
    palette='Set2',          # 调色板
    diag_kind='kde',         # 对角线图形类型:hist, kde
    markers=['o', 's', '^'], # 不同类别的标记
    plot_kws={'alpha': 0.7, 's': 50},
    diag_kws={'fill': True, 'alpha': 0.3},
    height=2.5
)

# 添加相关性系数
corr_matrix = iris.select_dtypes(include=[np.number]).corr()
for i, j in zip(*np.triu_indices_from(iris_pair.axes, 1)):
    corr = corr_matrix.iloc[i, j]
    iris_pair.axes[i, j].annotate(
        f'ρ = {corr:.2f}',
        xy=(0.5, 0.9),
        xycoords='axes fraction',
        ha='center',
        fontsize=10,
        color='red' if abs(corr) > 0.5 else 'black'
    )

iris_pair.fig.suptitle('鸢尾花数据集成对关系分析', y=1.02, fontsize=16)
plt.tight_layout()
plt.show()

sns.pairplot 一键生成了所有数值变量之间的散点图矩阵,并在对角线上展示了每个变量的分布(KDE图),是进行探索性数据分析(EDA)的利器。

四、分类数据可视化

比较不同类别组之间的数据分布是常见的分析需求。Seaborn为此设计了一系列专为分类数据优化的图表。

# 创建分类数据可视化
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
fig.suptitle('Seaborn分类数据可视化', fontsize=18, fontweight='bold')

# 准备数据
titanic_sample = titanic.dropna(subset=['age', 'fare'])

# 1. 箱线图
sns.boxplot(
    data=titanic_sample,
    x='class',
    y='age',
    hue='sex',
    palette='Set3',
    ax=axes[0, 0]
)
axes[0, 0].set_title('箱线图:船舱等级与年龄')
axes[0, 0].set_xlabel('船舱等级')
axes[0, 0].set_ylabel('年龄')

# 2. 小提琴图
sns.violinplot(
    data=titanic_sample,
    x='class',
    y='age',
    hue='sex',
    split=True,          # 分割小提琴图
    palette='pastel',
    inner='quartile',    # 内部显示四分位数
    ax=axes[0, 1]
)
axes[0, 1].set_title('小提琴图:年龄分布')
axes[0, 1].legend().remove()

# 3. 增强箱线图
sns.boxenplot(
    data=titanic_sample,
    x='class',
    y='fare',
    hue='sex',
    palette='Set2',
    k_depth='proportion',  # 显示更多分位数
    ax=axes[0, 2]
)
axes[0, 2].set_title('增强箱线图:票价分布')
axes[0, 2].set_ylabel('票价')

# 4. 点图
sns.pointplot(
    data=titanic_sample,
    x='class',
    y='age',
    hue='sex',
    palette='husl',
    dodge=True,           # 分组点分离显示
    markers=['o', 's'],   # 不同标记
    linestyles=['-', '--'],  # 不同线型
    capsize=0.1,          # 误差棒帽宽度
    errwidth=1.5,         # 误差棒宽度
    ax=axes[1, 0]
)
axes[1, 0].set_title('点图:平均年龄比较')
axes[1, 0].legend(title='性别', loc='upper right')

# 5. 条形图
sns.barplot(
    data=titanic,
    x='class',
    y='survived',
    hue='sex',
    palette='coolwarm',
    ci='sd',              # 误差棒:标准差
    capsize=0.1,
    errcolor='.2',
    errwidth=2,
    ax=axes[1, 1]
)
axes[1, 1].set_title('条形图:生存率比较')
axes[1, 1].set_ylabel('生存率')
axes[1, 1].legend(title='性别')

# 6. 计数图
sns.countplot(
    data=titanic,
    x='class',
    hue='alive',
    palette='Set1',
    ax=axes[1, 2]
)
axes[1, 2].set_title('计数图:生存状态分布')
axes[1, 2].legend(title='是否存活')

plt.tight_layout()
plt.show()

从展示分布细节的小提琴图 (violinplot),到展示更多分位数的增强箱线图 (boxenplot),再到用于比较均值的点图 (pointplot),Seaborn为不同的比较场景提供了最合适的图表类型。其条形图 (barplot) 和计数图 (countplot) 更是直接集成了误差估计和计数功能,无需手动聚合数据。

五、分布数据可视化

理解单个变量的分布特性是数据分析的基础。直方图和密度图是主要工具,但Seaborn提供了更丰富、更精致的变体。

# 创建分布可视化
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
fig.suptitle('Seaborn分布数据可视化', fontsize=18, fontweight='bold')

# 1. 直方图
sns.histplot(
    data=tips,
    x='total_bill',
    bins=20,
    kde=True,           # 添加核密度估计
    color='skyblue',
    edgecolor='black',
    linewidth=1,
    ax=axes[0, 0]
)
axes[0, 0].set_title('直方图:账单金额分布')
axes[0, 0].set_xlabel('账单金额')

# 2. 核密度估计图
sns.kdeplot(
    data=tips,
    x='total_bill',
    hue='time',         # 按用餐时间分类
    fill=True,          # 填充颜色
    alpha=0.3,
    palette='Set2',
    ax=axes[0, 1]
)
axes[0, 1].set_title('KDE图:按用餐时间分布')
axes[0, 1].set_xlabel('账单金额')

# 3. 累积分布图
sns.ecdfplot(
    data=tips,
    x='total_bill',
    hue='day',
    palette='viridis',
    stat='proportion',  # 显示比例而非计数
    ax=axes[0, 2]
)
axes[0, 2].set_title('经验累积分布图')
axes[0, 2].set_xlabel('账单金额')
axes[0, 2].set_ylabel('累积比例')

# 4. 双变量核密度估计
sns.kdeplot(
    data=tips,
    x='total_bill',
    y='tip',
    fill=True,
    thresh=0,           # 填充阈值
    levels=10,          # 等高线级别数
    cmap='Reds',
    ax=axes[1, 0]
)
axes[1, 0].set_title('双变量KDE:账单与小费关系')
axes[1, 0].set_xlabel('账单金额')
axes[1, 0].set_ylabel('小费金额')

# 5. 分布对比图
sns.displot(
    data=tips,
    x='total_bill',
    hue='sex',
    kind='kde',         # 类型:hist, kde, ecdf
    fill=True,
    palette='husl',
    height=4,
    aspect=1.5,
    rug=True,           # 添加地毯图
    multiple='layer'    # 显示方式:layer, stack, fill
)
plt.title('分布对比图:按性别', fontsize=14)
plt.show()

# 6. 蜂群图(替代散点图,显示分布密度)
fig, ax = plt.subplots(figsize=(8, 6))
sns.swarmplot(
    data=tips,
    x='day',
    y='total_bill',
    hue='sex',
    palette='Set3',
    dodge=True,         # 分离不同类别
    size=4,
    alpha=0.7,
    ax=ax
)
ax.set_title('蜂群图:每日账单金额分布')
ax.legend(title='性别')
plt.tight_layout()
plt.show()

histplot 替代了传统的 hist,并直接集成KDE。kdeplot 可以轻松绘制单变量或多变量的平滑密度估计。ecdfplot(经验累积分布函数图)对于比较不同组别的整体分布非常有效。swarmplot(蜂群图)则在显示所有数据点的同时,避免了重叠,清晰展示了分布密度。

六、高级网格功能

当需要基于数据子集创建多个相同类型的图表矩阵时,Seaborn的网格系统(FacetGrid, PairGrid, JointGrid)提供了无与伦比的灵活性。

1. FacetGrid:分面网格

FacetGrid 允许你根据数据中的一个或多个分类变量,将数据分割到不同的子图中。

# 创建分面网格
g = sns.FacetGrid(
    data=tips,
    row='sex',           # 按行分组
    col='time',          # 按列分组
    hue='smoker',        # 颜色分组
    palette='Set2',
    height=4,
    aspect=1.2,
    margin_titles=True   # 标题在外侧
)

# 映射绘图函数
g.map(sns.scatterplot, 'total_bill', 'tip', alpha=0.7, s=60)
g.map(sns.regplot, 'total_bill', 'tip', scatter=False, ci=None, color='.3')

# 添加图例
g.add_legend(title='是否吸烟')

# 设置轴标签
g.set_axis_labels('账单金额', '小费金额')
g.set_titles(row_template='{row_name}性', col_template='{col_name}餐')

# 调整布局
g.fig.suptitle('分面网格:多维度数据分析', y=1.02, fontsize=16)
plt.tight_layout()
plt.show()

2. PairGrid:定制成对图

pairplot 相比,PairGrid 赋予了你对子图中每个位置绘制何种图表的完全控制权。

# 创建定制化的成对图
g = sns.PairGrid(
    data=iris,
    hue='species',
    palette='husl',
    height=2.5,
    diag_sharey=False    # 对角线不共享y轴
)

# 自定义对角线、上三角、下三角的图形
g.map_diag(sns.histplot, kde=True, fill=True, alpha=0.5)
g.map_upper(sns.scatterplot, alpha=0.7, s=40, edgecolor='white', linewidth=0.5)
g.map_lower(sns.kdeplot, fill=True, levels=5, alpha=0.5)

# 添加图例
g.add_legend(title='鸢尾花种类')

# 添加标题
g.fig.suptitle('定制成对图:鸢尾花特征分析', y=1.02, fontsize=16)
plt.tight_layout()
plt.show()

3. JointGrid:高级联合分布图

JointGridjointplot 的底层构建块,提供了更细致的控制,允许你分别定制主图、x轴边缘图和y轴边缘图。

# 创建高级联合分布图
g = sns.JointGrid(
    data=tips,
    x='total_bill',
    y='tip',
    height=8,
    ratio=5
)

# 分别设置主图、边缘图
g.plot_joint(sns.scatterplot, hue=tips['size'], palette='viridis', size=tips['size'],
             sizes=(20, 200), alpha=0.6, edgecolor='white', linewidth=0.5)

g.plot_marginals(sns.histplot, kde=True, fill=True, alpha=0.5, color='steelblue')

# 添加回归线和核密度估计
sns.regplot(x='total_bill', y='tip', data=tips, scatter=False, ax=g.ax_joint,
            color='red', linewidth=2)

g.figure.suptitle('高级联合分布图:小费与账单关系', y=1.02, fontsize=16)
plt.tight_layout()
plt.show()

七、统计图表与热力图

热力图是展示矩阵数据的绝佳方式,常用于显示相关性矩阵或任何二维表格数据。Seaborn的 heatmapclustermap 功能全面。

# 创建热力图和聚类图
fig, axes = plt.subplots(2, 2, figsize=(14, 12))
fig.suptitle('热力图与聚类分析', fontsize=18, fontweight='bold')

# 1. 相关矩阵热力图
iris_numeric = iris.select_dtypes(include=[np.number])
corr_matrix = iris_numeric.corr()

sns.heatmap(
    data=corr_matrix,
    annot=True,            # 显示数值
    fmt='.2f',            # 数值格式
    cmap='coolwarm',      # 颜色映射
    center=0,             # 中心值
    square=True,          # 正方形单元
    linewidths=1,         # 单元边界线宽
    cbar_kws={'shrink': 0.8},  # 颜色条设置
    ax=axes[0, 0]
)
axes[0, 0].set_title('相关矩阵热力图')

# 2. 聚类热力图
sns.clustermap(
    iris_numeric,
    standard_scale=1,     # 标准化(按列)
    cmap='viridis',
    figsize=(8, 8),
    dendrogram_ratio=0.2, # 树状图比例
    cbar_pos=(0.02, 0.8, 0.03, 0.18),  # 颜色条位置
    row_cluster=True,     # 对行聚类
    col_cluster=True      # 对列聚类
)
plt.suptitle('聚类热力图:鸢尾花数据集', y=1.02, fontsize=14)
plt.show()

# 3. 分面热力图
# 创建模拟数据
np.random.seed(42)
data_facet = pd.DataFrame({
    'Group': np.repeat(['A', 'B', 'C'], 20),
    'Month': np.tile(['Jan', 'Feb', 'Mar', 'Apr', 'May'], 12),
    'Value': np.random.randn(60).cumsum() + 20
})

# 数据透视
pivot_data = data_facet.pivot_table(
    index='Group',
    columns='Month',
    values='Value',
    aggfunc='mean'
)

sns.heatmap(
    data=pivot_data,
    annot=True,
    fmt='.1f',
    cmap='YlOrRd',
    linewidths=0.5,
    ax=axes[0, 1]
)
axes[0, 1].set_title('分面热力图:各组月度数据')

# 4. 时间序列热力图
# 创建时间序列数据
dates = pd.date_range('2023-01-01', periods=50, freq='D')
time_series = pd.DataFrame({
    'date': dates,
    'value': np.sin(np.linspace(0, 10*np.pi, 50)) + np.random.randn(50)*0.3
})
time_series['day'] = time_series['date'].dt.day
time_series['week'] = time_series['date'].dt.isocalendar().week

# 数据透视
heatmap_data = time_series.pivot_table(
    index='week',
    columns='day',
    values='value',
    aggfunc='mean'
)

sns.heatmap(
    data=heatmap_data,
    cmap='RdYlBu',
    center=0,
    square=True,
    cbar_kws={'label': '数值'},
    ax=axes[1, 0]
)
axes[1, 0].set_title('时间序列热力图')
axes[1, 0].set_xlabel('日')
axes[1, 0].set_ylabel('周')

# 5. 二元变量热力图
from scipy.cluster.hierarchy import linkage

# 计算链接矩阵
linkage_matrix = linkage(iris_numeric.T, method='ward')

# 绘制层次聚类热力图
sns.heatmap(
    data=iris_numeric,
    cmap='Spectral',
    yticklabels=False,  # 隐藏y轴标签
    cbar_kws={'label': '标准化值'},
    ax=axes[1, 1]
)
axes[1, 1].set_title('层次聚类热力图')

plt.tight_layout()
plt.show()

clustermap 不仅绘制热力图,还通过层次聚类对行和列进行重新排序,并以树状图展示聚类结果,非常适合寻找数据中的模式。

八、实用工具与技巧

1. 颜色管理

颜色是可视化中传递信息的重要载体。Seaborn提供了丰富的调色板系统,并允许轻松定制。

# 颜色调色板演示
palettes = {
    '分类调色板': ['Set3', 'Set2', 'Paired', 'husl'],
    '顺序调色板': ['viridis', 'plasma', 'summer', 'wistia'],
    '发散调色板': ['coolwarm', 'RdBu', 'Spectral', 'icefire']
}

fig, axes = plt.subplots(3, 4, figsize=(15, 8))
fig.suptitle('Seaborn颜色调色板展示', fontsize=16, fontweight='bold')

for i, (palette_type, palette_list) in enumerate(palettes.items()):
    for j, palette_name in enumerate(palette_list):
        ax = axes[i, j]
        # 获取调色板
        current_palette = sns.color_palette(palette_name, n_colors=10)

        # 绘制调色板
        sns.palplot(current_palette, ax=ax)

        # 设置标题
        if i == 0:
            ax.set_title(palette_name, fontsize=12)

        # 添加调色板类型标签
        if j == 0:
            ax.set_ylabel(palette_type, fontsize=12, rotation=0, labelpad=40)

        ax.axis('off')

plt.tight_layout()
plt.show()

2. 样式管理

Seaborn预置了几种精美的绘图样式,可以快速改变图表的外观。

# 不同样式对比
styles = ['darkgrid', 'whitegrid', 'dark', 'white', 'ticks']
datasets = [tips, iris, penguins.dropna()]

fig, axes = plt.subplots(len(styles), len(datasets), figsize=(15, 12))

for i, style in enumerate(styles):
    for j, data in enumerate(datasets):
        sns.set_style(style)
        ax = axes[i, j]

        # 选择不同的绘图类型
        if j == 0:
            sns.histplot(data=tips, x='total_bill', kde=True, ax=ax, color='steelblue')
            title = f'Tips - {style}'
        elif j == 1:
            sns.scatterplot(data=iris, x='sepal_length', y='sepal_width',
                           hue='species', ax=ax, s=50, alpha=0.7)
            title = f'Iris - {style}'
        else:
            sns.boxplot(data=penguins.dropna(), x='species', y='body_mass_g',
                       hue='sex', ax=ax)
            title = f'Penguins - {style}'

        ax.set_title(title, fontsize=10)
        ax.legend().set_visible(False)

plt.suptitle('不同样式对比', fontsize=16, y=1.02)
plt.tight_layout()

# 恢复默认样式
sns.set_theme()
plt.show()

3. 实用函数集合

将常用的绘图逻辑封装成函数,可以极大提升分析效率。下面是一个创建高级仪表板的示例函数。

def create_advanced_dashboard(data, target_col):
    """
    创建高级可视化仪表板
    """
    # 创建图形
    fig = plt.figure(figsize=(20, 15))

    # 1. 相关矩阵热力图
    ax1 = plt.subplot(3, 3, 1)
    numeric_data = data.select_dtypes(include=[np.number])
    correlation = numeric_data.corr()
    sns.heatmap(correlation, annot=True, fmt='.2f', cmap='coolwarm',
                center=0, ax=ax1, cbar_kws={'shrink': 0.8})
    ax1.set_title('特征相关矩阵')

    # 2. 目标变量分布
    ax2 = plt.subplot(3, 3, 2)
    if target_col in numeric_data.columns:
        sns.histplot(data=data, x=target_col, kde=True, ax=ax2,
                    color='skyblue', fill=True)
    else:
        sns.countplot(data=data, x=target_col, ax=ax2, palette='Set2')
    ax2.set_title(f'{target_col} 分布')

    # 3. 箱线图矩阵
    ax3 = plt.subplot(3, 3, 3)
    numeric_cols = numeric_data.columns.tolist()
    if len(numeric_cols) > 0:
        # 标准化数据用于箱线图
        normalized_data = (numeric_data - numeric_data.mean()) / numeric_data.std()
        sns.boxplot(data=normalized_data.melt(), x='variable', y='value', ax=ax3)
        ax3.set_xticklabels(ax3.get_xticklabels(), rotation=45)
        ax3.set_title('特征箱线图')

    # 4. 成对关系图(简化版)
    ax4 = plt.subplot(3, 3, (4, 6))
    if len(numeric_cols) >= 2:
        pair_cols = numeric_cols[:min(4, len(numeric_cols))]
        pair_data = data[pair_cols].dropna()
        if target_col in data.columns:
            hue_col = target_col
        else:
            hue_col = None

        sns.pairplot(data=data, vars=pair_cols, hue=hue_col,
                    diag_kind='kde', plot_kws={'alpha': 0.6})
        plt.suptitle('成对关系分析', y=1.02)

    # 5. 小提琴图矩阵
    ax7 = plt.subplot(3, 3, 7)
    if target_col in data.columns:
        # 选择一个数值列
        num_col = next((col for col in numeric_cols if col != target_col), None)
        if num_col:
            sns.violinplot(data=data, x=target_col, y=num_col,
                          palette='Set3', ax=ax7)
            ax7.set_title(f'{num_col} 按 {target_col} 分布')

    # 6. 散点图矩阵
    ax8 = plt.subplot(3, 3, 8)
    if len(numeric_cols) >= 2:
        x_col, y_col = numeric_cols[0], numeric_cols[1]
        if target_col in data.columns:
            hue_col = target_col
            sns.scatterplot(data=data, x=x_col, y=y_col, hue=hue_col,
                           size=hue_col if hue_col in numeric_cols else None,
                           sizes=(20, 200), alpha=0.6, ax=ax8)
        else:
            sns.scatterplot(data=data, x=x_col, y=y_col, ax=ax8)
        ax8.set_title(f'{x_col} vs {y_col}')

    # 7. 分布对比
    ax9 = plt.subplot(3, 3, 9)
    if target_col in data.columns and len(numeric_cols) > 0:
        col_to_plot = numeric_cols[0]
        sns.kdeplot(data=data, x=col_to_plot, hue=target_col,
                   fill=True, alpha=0.3, ax=ax9)
        ax9.set_title(f'{col_to_plot} 分布对比')

    plt.suptitle('高级数据探索仪表板', fontsize=20, y=1.02)
    plt.tight_layout()
    return fig

# 使用示例
# fig = create_advanced_dashboard(titanic, 'survived')
# plt.show()

九、今日练习任务

1. 基础练习

# 任务1:使用penguins数据集
# - 创建物种与性别关系的分面图
# - 绘制身体质量(body_mass_g)的分布图(按物种分类)
# - 创建喙长与喙宽的联合分布图

# 任务2:自定义调色板
# - 创建自定义颜色调色板
# - 应用自定义调色板到至少2种不同的图表

# 任务3:数据洞察
# - 从titanic数据集中找出3个有趣的可视化洞察
# - 用合适的图表展示这些洞察

2. 进阶挑战

"""
挑战1:创建交互式仪表板
- 使用Seaborn创建多图表仪表板
- 实现图表间的联动效果(可考虑使用mplcursors)
- 添加动态数据更新功能

挑战2:大数据可视化优化
- 对超过10万行的数据集进行高效可视化
- 使用采样、聚合或密度图优化性能
- 比较不同可视化方法的性能

挑战3:自定义图表主题
- 创建公司/品牌的专属图表主题
- 实现完整的样式配置(颜色、字体、网格等)
- 将主题打包为可复用的函数
"""

3. 实用项目

"""
项目:电子商务数据分析仪表板
使用以下模拟数据创建完整的分析仪表板:

1. 用户行为分析
   - 用户访问时间分布
   - 页面浏览深度分析
   - 转化漏斗可视化

2. 销售分析
   - 销售趋势与季节性
   - 产品类别热力图
   - 客户分群可视化

3. 营销效果评估
   - 渠道效果对比
   - 营销活动ROI分析
   - 客户生命周期价值分布
"""

总结

通过本文的探索,我们深入了解了Seaborn在数据科学可视化领域的强大能力。从基础的散点图、条形图,到高级的网格系统、聚类热力图,Seaborn通过简洁的API将复杂的统计图形变得触手可及。其与Pandas的无缝集成,使得从DataFrame到出版级图表的工作流异常流畅。

记住,优秀的可视化不仅仅是让图表看起来漂亮,更是为了清晰、准确、高效地传达数据背后的故事。多练习文中的代码,尝试完成练习和挑战,你将成为一名真正的数据叙事者。欢迎在云栈社区分享你的可视化作品,与其他开发者共同交流成长!




上一篇:Incus 6.21发布:重要安全修复与自动化增强,容器管理更高效
下一篇:开源跨平台工具 iDescriptor 使用指南:轻松管理你的iPhone与iPad
您需要登录后才可以回帖 登录 | 立即注册

手机版|小黑屋|网站地图|云栈社区 ( 苏ICP备2022046150号-2 )

GMT+8, 2026-1-26 18:43 , Processed in 0.389013 second(s), 38 queries , Gzip On.

Powered by Discuz! X3.5

© 2025-2026 云栈社区.

快速回复 返回顶部 返回列表