{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-05-06T11:49:40.195103Z",
     "start_time": "2025-05-06T11:49:40.193162Z"
    }
   },
   "source": [
    "# 代码5-13\n",
    "# 导库\n",
    "from matplotlib import pyplot as plt\n",
    "import pandas as pd\n",
    "import seaborn as sns\n",
    "import warnings\n",
    "# 忽略所有警告\n",
    "warnings.filterwarnings(\"ignore\")"
   ],
   "outputs": [],
   "execution_count": 1
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T11:49:40.215751Z",
     "start_time": "2025-05-06T11:49:40.205742Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 设置中文字体\n",
    "from matplotlib import font_manager as fm\n",
    "import matplotlib as mpl\n",
    "font_path = '/System/Library/Fonts/STHeiti Medium.ttc'\n",
    "my_font = fm.FontProperties(fname=font_path)\n",
    "mpl.rcParams['font.family'] = my_font.get_name()\n",
    "mpl.rcParams['axes.unicode_minus'] = False"
   ],
   "id": "1fdc04b40026a38b",
   "outputs": [],
   "execution_count": 2
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T11:49:40.291504Z",
     "start_time": "2025-05-06T11:49:40.262025Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 加载数据\n",
    "hr = pd.read_csv('./data/hr.csv', encoding='gbk')\n",
    "hr.head(3)"
   ],
   "id": "c1cbb2b07efac1d",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "   用户编号   满意度    评分  总项目数  每月平均工作小时数（小时）  工龄（年）  工作事故  离职  5年内升职   部门 薪资\n",
       "0     1  0.38  0.53     2            157      3     0   1      0  销售部  低\n",
       "1     2  0.80  0.86     5            242      6     0   1      0  销售部  中\n",
       "2     3  0.11  0.88     7            242      4     0   1      0  销售部  中"
      ],
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>用户编号</th>\n",
       "      <th>满意度</th>\n",
       "      <th>评分</th>\n",
       "      <th>总项目数</th>\n",
       "      <th>每月平均工作小时数（小时）</th>\n",
       "      <th>工龄（年）</th>\n",
       "      <th>工作事故</th>\n",
       "      <th>离职</th>\n",
       "      <th>5年内升职</th>\n",
       "      <th>部门</th>\n",
       "      <th>薪资</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>0.38</td>\n",
       "      <td>0.53</td>\n",
       "      <td>2</td>\n",
       "      <td>157</td>\n",
       "      <td>3</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>销售部</td>\n",
       "      <td>低</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2</td>\n",
       "      <td>0.80</td>\n",
       "      <td>0.86</td>\n",
       "      <td>5</td>\n",
       "      <td>242</td>\n",
       "      <td>6</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>销售部</td>\n",
       "      <td>中</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3</td>\n",
       "      <td>0.11</td>\n",
       "      <td>0.88</td>\n",
       "      <td>7</td>\n",
       "      <td>242</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>销售部</td>\n",
       "      <td>中</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 3
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 📊 分析员工满意度与平均每月工作时长的关系\n",
    "\n",
    "本程序使用 Matplotlib 绘制散点图，展示不同薪资水平的员工在满意度与每月平均工作时长之间的关系。主要流程如下：\n",
    "\n",
    "1. **数据准备**\n",
    "   从员工数据集中提取前 100 条记录，作为可视化的数据样本。\n",
    "\n",
    "2. **定义颜色映射**\n",
    "   为每种薪资水平指定唯一颜色，以便在散点图中分类显示。\n",
    "\n",
    "3. **按薪资分组并绘制散点图**\n",
    "   遍历每个薪资分组的子集，将“每月平均工作小时数”作为 X 轴，“满意度”作为 Y 轴，绘制分类散点图。\n",
    "\n",
    "4. **设置图例**\n",
    "   为图表添加图例，以显示各薪资水平所对应的颜色，增强可读性。\n",
    "\n",
    "5. **设置坐标轴与图表标题**\n",
    "   添加 X 轴、Y 轴标签以及图表主标题，确保图表含义清晰明确。\n",
    "\n",
    "6. **显示图表**\n",
    "   使用 `plt.show()` 命令将绘制好的图表展示出来。"
   ],
   "id": "4af79d7680d813cf"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T11:49:40.489601Z",
     "start_time": "2025-05-06T11:49:40.370521Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 从 hr 数据集中选取前 100 条记录，用作绘图样本数据\n",
    "data = hr.head(100)\n",
    "# 为每个唯一的薪资水平指定一种颜色，并构造映射字典\n",
    "# zip 将 ['高', '中', '低'] 与 ['b', 'y', 'r'] 一一对应\n",
    "color_map = dict(zip(data['薪资'].unique(), ['b', 'y', 'r']))\n",
    "# 遍历每一个薪资等级的数据子集，分别绘制散点图\n",
    "for species, group in data.groupby('薪资'):\n",
    "    plt.scatter(\n",
    "        group['每月平均工作小时数（小时）'],  # x：横坐标为每月工作时长\n",
    "        group['满意度'],                   # y：纵坐标为满意度\n",
    "        color=color_map[species],         # color：根据薪资映射的颜色\n",
    "        alpha=0.4,                        # alpha：点的透明度，值越小越透明\n",
    "        edgecolors=None,                  # edgecolors：点边缘颜色，None 表示无边\n",
    "        label=species                     # label：图例中显示的分类名称\n",
    "    )\n",
    "# 添加图例，显示每种薪资等级对应的颜色\n",
    "# frameon=True 表示图例带有边框；title 设置图例标题为“薪资”\n",
    "plt.legend(frameon=True, title='薪资')\n",
    "# 设置横轴标签文本\n",
    "plt.xlabel('平均每个月工作时长（小时）')\n",
    "# 设置纵轴标签文本\n",
    "plt.ylabel('满意度水平')\n",
    "# 设置图表的主标题\n",
    "plt.title('满意度水平与平均每个月工作小时')\n",
    "# 展示最终绘图结果\n",
    "plt.show()"
   ],
   "id": "adbad6783d7276f6",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ],
      "image/png": "[encoded data, 25808 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "execution_count": 4
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 📊 员工满意度与平均每月工作时长的可视化流程说明\n",
    "\n",
    "本程序用于分析员工“满意度”与“每月平均工作时长”之间的关系，主要流程如下：\n",
    "\n",
    "1. **使用 Seaborn 的 `lmplot` 函数绘制散点图**\n",
    "   - 横轴表示“每月平均工作小时数”，纵轴表示“满意度”。\n",
    "   - 通过设置 `hue='薪资'`，将不同薪资等级的员工使用不同颜色区分。\n",
    "   - 设置 `fit_reg=False`，表示不绘制线性回归拟合线，仅展示散点。\n",
    "\n",
    "2. **设置图表的坐标轴标签**\n",
    "   - 为 X 轴添加“平均每个月工作时长（小时）”标签。\n",
    "   - 为 Y 轴添加“满意度水平”标签。\n",
    "\n",
    "3. **设置图表标题**\n",
    "   - 图表的主标题为“满意度水平与平均每个月工作小时”。\n",
    "\n",
    "4. **显示图表**\n",
    "   - 最后通过 `plt.show()` 将图表展示出来。"
   ],
   "id": "bdc8a082799e5bd5"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T11:49:40.976545Z",
     "start_time": "2025-05-06T11:49:40.679560Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 使用 seaborn 的 lmplot 方法绘制散点图，展示“满意度”与“每月平均工作时长”的关系\n",
    "sns.lmplot(\n",
    "    '每月平均工作小时数（小时）',  # 第一个参数：x 轴变量，表示每月工作时长\n",
    "    '满意度',                   # 第二个参数：y 轴变量，表示员工满意度\n",
    "    data,                       # data：传入的数据集（前面应定义为包含这些字段的 DataFrame）\n",
    "    hue='薪资',                 # hue：根据“薪资”列的值分类着色\n",
    "    fit_reg=False,              # fit_reg：是否绘制回归拟合线，False 表示不绘制，仅显示散点\n",
    "    height=4                    # height：图像高度（单位为英寸），控制图表整体大小\n",
    ")\n",
    "# 设置 x 轴的标签文本\n",
    "plt.xlabel('平均每个月工作时长（小时）')  # 表示横轴单位与含义\n",
    "# 设置 y 轴的标签文本\n",
    "plt.ylabel('满意度水平')  # 表示纵轴的单位与含义\n",
    "# 设置图表的标题\n",
    "plt.title('满意度水平与平均每个月工作小时')\n",
    "# 显示图表窗口\n",
    "plt.show()"
   ],
   "id": "4944828754147229",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Figure size 334x288 with 1 Axes>"
      ],
      "image/png": "[encoded data, 25740 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "execution_count": 5
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 📊 使用 Matplotlib 绘制多条直线图\n",
    "\n",
    "本程序演示如何使用 Matplotlib 库绘制多条直线图，并设置图表标题。主要流程如下：\n",
    "\n",
    "1. **导入 NumPy 库并设置图形参数**\n",
    "   - 导入 NumPy 用于生成数值序列；\n",
    "   - 通过设置 `plt.rcParams['axes.unicode_minus'] = False`，确保负号可以在图表中正确显示。\n",
    "\n",
    "2. **构造数据**\n",
    "   - 使用 `np.arange()` 创建 x 轴的数值序列；\n",
    "   - 通过对 x 加常数分别生成 y1、y2、y3 三组直线数据。\n",
    "\n",
    "3. **绘制多条直线图**\n",
    "   - 使用 `plt.plot()` 分别绘制三条直线，分别对应 y1、y2 和 y3。\n",
    "\n",
    "4. **添加图表标题**\n",
    "   - 使用 `plt.title()` 添加主标题，说明图表展示内容。\n",
    "\n",
    "5. **显示图表**\n",
    "   - 使用 `plt.show()` 将图表可视化。"
   ],
   "id": "c7469a989192d20d"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T11:49:41.060927Z",
     "start_time": "2025-05-06T11:49:40.992453Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 导入 numpy 数组处理库\n",
    "import numpy as np\n",
    "# 设置图形显示参数，使负号正常显示（避免出现乱码或方块）\n",
    "plt.rcParams['axes.unicode_minus'] = False\n",
    "# 创建一个从 1 到 9，步长为 2 的数组，作为 x 轴数据\n",
    "x = np.arange(1, 10, 2)  # 输出: array([1, 3, 5, 7, 9])\n",
    "# 构造三条直线的 y 值：分别为 x+1, x+3, x+5\n",
    "y1 = x + 1\n",
    "y2 = x + 3\n",
    "y3 = x + 5\n",
    "# 设置图表标题为“Matplotlib库的绘图风格”\n",
    "plt.title('Matplotlib库的绘图风格')\n",
    "# 绘制第一条直线（x, y1）\n",
    "plt.plot(x, y1)\n",
    "# 绘制第二条直线（x, y2）\n",
    "plt.plot(x, y2)\n",
    "# 绘制第三条直线（x, y3）\n",
    "plt.plot(x, y3)\n",
    "# 显示图表\n",
    "plt.show()"
   ],
   "id": "be0e741a1c4e61e2",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ],
      "image/png": "[encoded data, 24776 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "execution_count": 6
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 📊 使用 Seaborn 绘制多条折线图并设置绘图风格\n",
    "\n",
    "本程序使用 Seaborn 库绘制三条折线图，同时设置图表风格和标题。流程如下：\n",
    "\n",
    "1. **设置 Seaborn 绘图风格**\n",
    "   - 使用 `darkgrid` 风格背景，使图表背景带有灰色网格；\n",
    "   - 设置字体为 `'SimHei'`（黑体）和 `'Arial'`，以确保支持中文和英文字体混合显示。\n",
    "\n",
    "2. **添加图表标题**\n",
    "   - 使用 `plt.title()` 设置图表标题，指明图表内容是 Seaborn 风格演示。\n",
    "\n",
    "3. **绘制三条折线图**\n",
    "   - 使用 `sns.lineplot()` 分别绘制三组数据曲线（y1、y2、y3 对应 x）；\n",
    "   - 默认线条颜色不同，可自动区分。\n",
    "\n",
    "4. **显示图表**\n",
    "   - 使用 `plt.show()` 展示最终绘图结果。"
   ],
   "id": "423cb70c4eb0b485"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T11:49:41.154619Z",
     "start_time": "2025-05-06T11:49:41.073407Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 设置 seaborn 的绘图风格为 darkgrid（背景为深色网格）\n",
    "# sns.set_style('darkgrid')\n",
    "# 设置字体为黑体（simhei）和 Arial，保证中英文均能显示\n",
    "# font.sans-serif 是设置无衬线字体优先级的参数\n",
    "# sns.set_style({'font.sans-serif': ['simhei', 'Arial']})\n",
    "# 设置图表主标题为“seaborn库的绘图风格”\n",
    "plt.title('seaborn库的绘图风格')\n",
    "# 使用 seaborn 绘制第一条折线图（x 对 y1）\n",
    "sns.lineplot(x, y1)\n",
    "# 使用 seaborn 绘制第二条折线图（x 对 y2）\n",
    "sns.lineplot(x, y2)\n",
    "# 使用 seaborn 绘制第三条折线图（x 对 y3）\n",
    "sns.lineplot(x, y3)\n",
    "# 显示图表\n",
    "plt.show()"
   ],
   "id": "2323bdfbb30c8f92",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ],
      "image/png": "[encoded data, 24608 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "execution_count": 7
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 📊 使用 Seaborn 的多种绘图风格进行对比展示\n",
    "\n",
    "本程序使用 Seaborn 的多个主题风格，分别绘制相同的三条折线图，并将它们放入一个图像的多个子图中进行展示对比，主要流程如下：\n",
    "\n",
    "1. **数据准备**\n",
    "   - 使用 `np.arange()` 创建 x 序列，并构造三组 y 序列作为三条线的 Y 轴数据。\n",
    "\n",
    "2. **封装绘图函数 `showLine()`**\n",
    "   - 封装绘图操作，将三条线的绘图过程统一到一个函数中，便于多次调用。\n",
    "\n",
    "3. **创建总图框 `figure()`**\n",
    "   - 设置画布大小为 12x8 英寸，用于容纳多个子图。\n",
    "\n",
    "4. **依次使用五种 Seaborn 风格绘制子图**\n",
    "   - 每种风格（`darkgrid`, `whitegrid`, `dark`, `white`, `ticks`）都对应一个子图；\n",
    "   - 使用 `with sns.axes_style(...)` 语法在局部应用样式；\n",
    "   - 每个子图通过 `add_subplot(2, 3, i)` 添加，形成 2 行 3 列的图像布局。\n",
    "\n",
    "5. **绘制一个自定义参数的子图**\n",
    "   - 在第六个子图中使用 `sns.set_style()` 设置额外参数（如字体和网格线颜色）；\n",
    "   - 演示如何修改 Seaborn 风格中的具体细节。\n",
    "\n",
    "6. **展示所有子图**\n",
    "   - 使用 `plt.show()` 一次性将全部子图显示出来。"
   ],
   "id": "8ab80b3585e278ef"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T11:49:41.914152Z",
     "start_time": "2025-05-06T11:49:41.167884Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 创建 x 序列：从 1 到 9，步长为 2\n",
    "x = np.arange(1, 10, 2)\n",
    "# 构造三条折线的数据\n",
    "y1 = x + 1\n",
    "y2 = x + 3\n",
    "y3 = x + 5\n",
    "# 封装绘图函数，绘制三条折线\n",
    "def showLine(flip=1):\n",
    "    sns.lineplot(x, y1)  # 绘制第一条线\n",
    "    sns.lineplot(x, y2)  # 绘制第二条线\n",
    "    sns.lineplot(x, y3)  # 绘制第三条线\n",
    "# 创建一个图像对象，设置整体图像大小为 12x8 英寸\n",
    "pic = plt.figure(figsize=(12, 8))\n",
    "# 使用 Seaborn 的 darkgrid 风格\n",
    "with sns.axes_style('darkgrid'):\n",
    "    pic.add_subplot(2, 3, 1)  # 添加第一个子图（第1行第1列）\n",
    "    showLine()\n",
    "    plt.title('darkgrid')\n",
    "# 使用 Seaborn 的 whitegrid 风格\n",
    "with sns.axes_style('whitegrid'):\n",
    "    pic.add_subplot(2, 3, 2)  # 添加第二个子图（第1行第2列）\n",
    "    showLine()\n",
    "    plt.title('whitegrid')\n",
    "# 使用 Seaborn 的 dark 风格\n",
    "with sns.axes_style('dark'):\n",
    "    pic.add_subplot(2, 3, 3)  # 添加第三个子图（第1行第3列）\n",
    "    showLine()\n",
    "    plt.title('dark')\n",
    "# 使用 Seaborn 的 white 风格\n",
    "with sns.axes_style('white'):\n",
    "    pic.add_subplot(2, 3, 4)  # 添加第四个子图（第2行第1列）\n",
    "    showLine()\n",
    "    plt.title('white')\n",
    "# 使用 Seaborn 的 ticks 风格\n",
    "with sns.axes_style('ticks'):\n",
    "    pic.add_subplot(2, 3, 5)  # 添加第五个子图（第2行第2列）\n",
    "    showLine()\n",
    "    plt.title('ticks')\n",
    "# 设置整体风格并修改字体和网格颜色等参数\n",
    "sns.set_style(\n",
    "    style='darkgrid',\n",
    "    rc={\n",
    "        'font.sans-serif': ['MicrosoftYaHei', 'SimHei'],  # 设置中文字体优先级\n",
    "        'grid.color': 'black'  # 修改网格线颜色为黑色\n",
    "    }\n",
    ")\n",
    "# 重设代码字体\n",
    "mpl.rcParams['font.family'] = my_font.get_name()\n",
    "\n",
    "# 添加第六个子图（第2行第3列）用于显示自定义风格效果\n",
    "pic.add_subplot(2, 3, 6)\n",
    "showLine()\n",
    "plt.title('修改参数')\n",
    "# 显示所有子图\n",
    "plt.show()"
   ],
   "id": "2797aac2500cb69d",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans.\n",
      "findfont: Generic family 'sans-serif' not found because none of the following families were found: MicrosoftYaHei, SimHei\n",
      "findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans.\n",
      "findfont: Generic family 'sans-serif' not found because none of the following families were found: MicrosoftYaHei, SimHei\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<Figure size 864x576 with 6 Axes>"
      ],
      "image/png": "[encoded data, 85884 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "execution_count": 8
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 📊 使用 Seaborn 的不同绘图上下文（plotting context）展示图表尺寸变化\n",
    "\n",
    "本程序演示 Seaborn 的四种绘图上下文配置对图表元素（如线宽、字体大小等）效果的影响，主要流程如下：\n",
    "\n",
    "1. **设置默认绘图风格**\n",
    "   - 使用 `sns.set()` 启用默认 Seaborn 风格（等价于 `set_theme()` 的基础版本）。\n",
    "\n",
    "2. **构造绘图数据**\n",
    "   - 创建 X 轴序列，以及三条 Y 序列，作为绘图数据。\n",
    "\n",
    "3. **定义绘图函数 `showLine()`**\n",
    "   - 将三条折线图绘图过程封装为函数，以便重复调用。\n",
    "\n",
    "4. **创建图像容器 `figure()`**\n",
    "   - 使用 `plt.figure()` 创建图形对象，并设置尺寸和 DPI 分辨率。\n",
    "\n",
    "5. **分别应用四种 `plotting_context` 上下文设置**\n",
    "   - 每种上下文类型（`paper`, `notebook`, `talk`, `poster`）定义了不同的图表元素尺寸标准；\n",
    "   - 在 2x2 子图布局中分别显示四种风格；\n",
    "   - 每个子图通过 `add_subplot()` 添加并配合 `with sns.plotting_context(...)` 局部生效。\n",
    "\n",
    "6. **显示图表**\n",
    "   - 使用 `plt.show()` 显示所有子图，方便直观比较上下文设置对图表尺寸和样式的影响。"
   ],
   "id": "12250374b656c2d0"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T11:49:42.368269Z",
     "start_time": "2025-05-06T11:49:41.935541Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 设置 seaborn 的默认样式（包括颜色、网格等），等同于 sns.set_theme()\n",
    "sns.set()\n",
    "# 构造横轴数据（x），以及三条纵轴数据（y1, y2, y3）\n",
    "x = np.arange(1, 10, 2)\n",
    "y1 = x + 1\n",
    "y2 = x + 3\n",
    "y3 = x + 5\n",
    "# 定义绘图函数，绘制三条折线图\n",
    "def showLine(flip=1):\n",
    "    sns.lineplot(x, y1)  # 第 1 条折线\n",
    "    sns.lineplot(x, y2)  # 第 2 条折线\n",
    "    sns.lineplot(x, y3)  # 第 3 条折线\n",
    "# 创建一个图形窗口，大小为 8x8 英寸，DPI 为 100\n",
    "pic = plt.figure(figsize=(8, 8), dpi=100)\n",
    "# 使用 paper 上下文样式（适用于论文，元素尺寸最小）\n",
    "with sns.plotting_context('paper'):\n",
    "    pic.add_subplot(2, 2, 1)  # 添加第 1 个子图（左上）\n",
    "    showLine()\n",
    "    plt.title('paper')  # 设置标题\n",
    "# 使用 notebook 上下文样式（默认值，适用于常规交互笔记本）\n",
    "with sns.plotting_context('notebook'):\n",
    "    pic.add_subplot(2, 2, 2)  # 添加第 2 个子图（右上）\n",
    "    showLine()\n",
    "    plt.title('notebook')\n",
    "# 使用 talk 上下文样式（适合展示或汇报，字体和线条更大）\n",
    "with sns.plotting_context('talk'):\n",
    "    pic.add_subplot(2, 2, 3)  # 添加第 3 个子图（左下）\n",
    "    showLine()\n",
    "    plt.title('talk')\n",
    "# 使用 poster 上下文样式（适合海报展示，元素最大）\n",
    "with sns.plotting_context('poster'):\n",
    "    pic.add_subplot(2, 2, 4)  # 添加第 4 个子图（右下）\n",
    "    showLine()\n",
    "    plt.title('poster')\n",
    "# 显示所有子图\n",
    "plt.show()"
   ],
   "id": "d2d2f1fa1e8642c4",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Figure size 800x800 with 4 Axes>"
      ],
      "image/png": "[encoded data, 107208 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "execution_count": 9
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 📐 使用 `sns.despine()` 控制图形边框的显示\n",
    "\n",
    "本程序展示了如何使用 Seaborn 提供的 `despine()` 方法控制图形边框（轴脊）的显示与隐藏。主要流程如下：\n",
    "\n",
    "1. **绘制折线图并去除边框**\n",
    "   - 使用 `sns.axes_style('white')` 设置背景为白色；\n",
    "   - 绘制多条折线图；\n",
    "   - 调用 `sns.despine()` 默认移除顶部和右侧边框；\n",
    "   - 设置标题为“控制图形边框”并显示图形。\n",
    "\n",
    "2. **绘制箱线图并定制边框控制参数**\n",
    "   - 使用 `np.random.normal()` 生成正态分布数据，作为箱线图输入；\n",
    "   - 使用 `sns.boxplot()` 绘制箱线图；\n",
    "   - 使用 `sns.despine(offset=10, left=False, bottom=False)` 调整边框：保留左侧和底部边框，同时设置边缘偏移；\n",
    "   - 设置标题并显示图形。\n",
    "\n",
    "该方法适用于提升图形美观性，常用于出版级或报告图表。"
   ],
   "id": "65ba0088b2026eda"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T11:57:19.019597Z",
     "start_time": "2025-05-06T11:57:18.785059Z"
    }
   },
   "cell_type": "code",
   "source": [
    "with sns.axes_style('white'):  # 设置 seaborn 风格为白色背景\n",
    "    showLine()  # 调用自定义函数绘制三条折线图\n",
    "    sns.despine()  # 默认移除上边框和右边框，提升图形简洁度\n",
    "    plt.title('控制图形边框',fontproperties=my_font)  # 设置图标题\n",
    "    # 重设代码字体\n",
    "plt.show()  # 显示图形\n",
    "\n",
    "with sns.axes_style('white'):  # 设置为白色背景\n",
    "    data = np.random.normal(size=(20, 6)) + np.arange(6) / 2  # 生成模拟数据：正态分布 + 偏移量\n",
    "    sns.boxplot(data=data)  # 绘制箱线图\n",
    "    sns.despine(offset=10, left=False, bottom=False)  # 控制边框显示，保留左边和下边，并设置偏移量\n",
    "        # 重设代码字体\n",
    "    plt.title('控制图形边框',fontproperties=my_font)  # 设置图标题\n",
    "\n",
    "plt.show()  # 显示图形"
   ],
   "id": "58eb0dfcf8353fee",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ],
      "image/png": "[encoded data, 23380 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ],
      "image/png": "[encoded data, 8772 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "execution_count": 20
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 🎨 显示当前 Seaborn 默认调色板\n",
    "\n",
    "本程序用于展示 Seaborn 当前默认的颜色调色板，流程如下：\n",
    "\n",
    "1. **获取当前默认调色板**\n",
    "   - 通过 `sns.color_palette()` 获取 Seaborn 当前使用的颜色列表。\n",
    "\n",
    "2. **可视化调色板**\n",
    "   - 使用 `sns.palplot()` 绘制颜色条，每种颜色显示为一个并排的色块；\n",
    "   - 可用于了解当前配色、选择视觉效果统一的颜色方案。\n",
    "\n",
    "该方法常用于数据可视化前的调色板预览或自定义配色设计。"
   ],
   "id": "65eb7cc9faeb4f06"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T11:52:14.159140Z",
     "start_time": "2025-05-06T11:52:14.105456Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 代码5-18\n",
    "sns.palplot(sns.color_palette())  # 显示当前 seaborn 默认的颜色调色板，每种颜色以色块形式排列展示"
   ],
   "id": "54053170c93453fc",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Figure size 720x72 with 1 Axes>"
      ],
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAjwAAABECAYAAACF4e8fAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAAAClklEQVR4nO3Zv0tWUQDG8WP4M0h7ExuDJic3g1pcgv6NaCiCgpbIMMcIgpaoQXpp6F+oOQLX2moPGpU30yB/INwWF4dy6bwnHj6f5Qz3Dg9cLnzhjHRd1xUAgGCnWg8AAKhN8AAA8QQPABBP8AAA8QQPABBP8AAA8UZPeuHBi/Uy2N4bxpahe716rXx7ebv1jGou3F0rd949aj2jihtvB2Wxv1Y+3cz8fov9tfL88fvWM6q5t3q1vHl6v/WMaq4vPytfX31sPaOai7culX6/33pGFZfnN8vC0kr5vP6k9ZQqFpZWysMPX1rPqKI3OVaWr8z/8fmJwTPY3isbW7v/dNT/5HB7s/WEqjZ/fW89oYr9jc1jZ6Lt4P+ulFJ+/hi0nlDV4c5+6wlV7ezstJ5QxcHe1rEz0WD3oPWEJlxpAQDxBA8AEE/wAADxBA8AEE/wAADxBA8AEE/wAADxBA8AEE/wAADxBA8AEE/wAADxBA8AEE/wAADxBA8AEE/wAADxBA8AEE/wAADxBA8AEE/wAADxBA8AEE/wAADxBA8AEE/wAADxBA8AEE/wAADxBA8AEE/wAADxBA8AEE/wAADxBA8AEE/wAADxBA8AEE/wAADxBA8AEE/wAADxBA8AEE/wAADxBA8AEE/wAADxBA8AEE/wAADxBA8AEE/wAADxBA8AEE/wAADxBA8AEE/wAADxBA8AEE/wAADxBA8AEE/wAADxRk96YXZmchg7mhmdmWs9oaq50+daT6hi4nx3dOZ+v5neVOsJVZ05O9t6QlWj0xOtJ1Q1PT3dekIV45P7R2ev8ZJ6ZqfGW0+oojc59tfnI13XdUPaAgDQhCstACCe4AEA4gkeACCe4AEA4gkeACCe4AEA4v0G2LZVRfld9xMAAAAASUVORK5CYII=\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "execution_count": 14
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 🎨 使用 `muted` 调色板展示 Seaborn 的配色风格\n",
    "\n",
    "本程序展示了如何使用 Seaborn 中的 `muted` 风格调色板，并以色块方式进行可视化。主要流程如下：\n",
    "\n",
    "1. **获取指定风格的调色板**\n",
    "   - 使用 `sns.color_palette('muted')` 加载 Seaborn 内置的 `muted`（柔和）色系调色板；\n",
    "   - 该调色板包含一组低饱和度、舒适柔和的配色，适合正式、低对比度的图表展示。\n",
    "\n",
    "2. **可视化调色板**\n",
    "   - 使用 `sns.palplot()` 绘制调色板，按顺序展示每种颜色的色块。\n",
    "\n",
    "该方法用于预览配色方案，便于统一图表风格或在实际绘图中指定配色参数。"
   ],
   "id": "d81c8bb09f0ffdae"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T11:50:42.143799Z",
     "start_time": "2025-05-06T11:50:42.093138Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 代码5-19\n",
    "palette = sns.color_palette('muted')  # 获取 seaborn 内置的 muted 柔和风格调色板\n",
    "sns.palplot(palette)  # 将调色板绘制为色块序列，便于视觉预览"
   ],
   "id": "6c8226f44519ba91",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Figure size 720x72 with 1 Axes>"
      ],
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAjwAAABECAYAAACF4e8fAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAAACpElEQVR4nO3ZL2uVUQDH8TP3T8O2yzbUZtmK+AJElnwHBqPIgskkThRExLAyLwiCGAwyjL4Hk8FkMc5iERl3494ZdN7ptdyqS2cHfnw+5YTnCb+nPHzhTIxGo1EBAAh2qvUAAIDaBA8AEE/wAADxBA8AEE/wAADxBA8AEG/quBfuvtwpvYPhSWw5cdv3L5bBi/XWM6pZuP26PPr0oPWMKm5uH5WVbrd83thoPaWKlW63vHn8rvWMam48uVpe3bveekY1t56+LV+efWg9o5oLdy6Xra2t1jOquHZlUFbXNsvO+4etp1SxurZZnn/82npGFXMzk2X90rl/Pj82eHoHw7LbzwyeUkr5M9htPaGq/V97rSdUMewNx2ev8ZJ6vu//aD2hqoO9b60nVHXUP2w9oap+v996QhXDn/vjM/PfWUopg8PfrSc04UoLAIgneACAeIIHAIgneACAeIIHAIgneACAeIIHAIgneACAeIIHAIgneACAeIIHAIgneACAeIIHAIgneACAeIIHAIgneACAeIIHAIgneACAeIIHAIgneACAeIIHAIgneACAeIIHAIgneACAeIIHAIgneACAeIIHAIgneACAeIIHAIgneACAeIIHAIgneACAeIIHAIgneACAeIIHAIgneACAeIIHAIgneACAeIIHAIgneACAeIIHAIgneACAeIIHAIgneACAeIIHAIgneACAeIIHAIgneACAeIIHAIgneACAeIIHAIg3ddwLy/PTJ7GjmVMLZ1tPqGpxZqn1hCqml4/G53LjJfXMLZ5pPaGq+aXzrSdUNdWZbT2hqk6n03pCFdOnJ8Zn5r+zlFIWZidbT6hibub/3zUxGo1GJ7QFAKAJV1oAQDzBAwDEEzwAQDzBAwDEEzwAQDzBAwDE+wt7f1RWg6E/yAAAAABJRU5ErkJggg==\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "execution_count": 12
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 🌈 使用 HLS 色彩空间生成的调色板\n",
    "\n",
    "本程序展示了如何使用 Seaborn 的 `hls` 色彩空间生成调色板，并以色块形式进行可视化。主要流程如下：\n",
    "\n",
    "1. **基于 HLS 色彩空间生成调色板**\n",
    "   - 调用 `sns.color_palette('hls', 8)` 生成一个包含 8 种颜色的调色板；\n",
    "   - HLS 表示色相（Hue）、亮度（Lightness）、饱和度（Saturation），生成的颜色鲜艳、分布均匀，适合分类图表。\n",
    "\n",
    "2. **可视化调色板**\n",
    "   - 使用 `sns.palplot()` 将调色板颜色展示为一排色块，便于视觉预览和配色选择。\n",
    "\n",
    "该方法常用于分类数据可视化（如柱状图、饼图、分类折线图）中的配色方案设计。"
   ],
   "id": "f356b0d01a1d79fc"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T11:51:18.192913Z",
     "start_time": "2025-05-06T11:51:18.090053Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 代码5-20\n",
    "sns.palplot(sns.color_palette('hls', 8))  # 使用 HLS 色彩空间生成 8 种颜色，并绘制为色块用于预览"
   ],
   "id": "1dc5b10ced0a755a",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Figure size 576x72 with 1 Axes>"
      ],
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAcwAAABECAYAAAAMTwWHAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAAACE0lEQVR4nO3YMYrUYBzG4W8l4ooIOpDOIp03sPIYXsA+hSfYYrEVLNJ7AY+wJ/AGdinsIrOCiIiBeAF13sLkc8LztMnA+y+GH+RiWZalAAB/daf2AAA4B4IJAAHBBICAYAJAQDABICCYABBoTr3w6fVVmW+PW2zZXPdmKOOHvvaM1XTPhvJu3O99L7uh9OPb2jNWMXSvSv9xrD1jNcPTrvTXY+0ZqxmuuvK+H2vPWM2LoStjf1N7xiqaw2V5cv38989O/Xi+PZb58/TPR/0v5h/7va2UUr7O+75vmr/UnrCa6edce8KqpuO+7/s27fu+efpee8LmfJIFgIBgAkBAMAEgIJgAEBBMAAgIJgAEBBMAAoIJAAHBBICAYAJAQDABICCYABAQTAAICCYABAQTAAKCCQABwQSAgGACQEAwASAgmAAQEEwACAgmAAQEEwACggkAAcEEgIBgAkBAMAEgIJgAEBBMAAgIJgAEBBMAAoIJAAHBBICAYAJAQDABICCYABAQTAAICCYABAQTAAKCCQABwQSAgGACQEAwASAgmAAQEEwACAgmAAQEEwACggkAAcEEgIBgAkBAMAEg0Jx84fFhix3VNPfa2hNW9bDZ931t86j2hNW0d0/+Pc9ae9j3fQ/afd/XtPdrT1hFc7j847OLZVmWDbcAwFnySRYAAoIJAAHBBICAYAJAQDABICCYABD4BdCuPnYaLCxVAAAAAElFTkSuQmCC\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "execution_count": 13
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 🎨 使用 `hls_palette()` 自定义亮度和饱和度的配色方案\n",
    "\n",
    "本程序通过 `sns.hls_palette()` 创建一个自定义 HLS 色彩空间的调色板，并进行可视化展示。主要流程如下：\n",
    "\n",
    "1. **生成自定义 HLS 调色板**\n",
    "   - 使用 `sns.hls_palette(8, l=0.3, s=0.8)` 生成 8 种颜色；\n",
    "   - `l=0.3` 设置亮度较低，使颜色更深；\n",
    "   - `s=0.8` 设置较高饱和度，使颜色更加鲜明。\n",
    "\n",
    "2. **可视化调色板**\n",
    "   - 使用 `sns.palplot()` 以色块形式展示自定义调色板；\n",
    "   - 该方法适合需要暗色背景或更强视觉对比的场景。\n",
    "\n",
    "通过调整 `l`（lightness）和 `s`（saturation）参数，可以根据具体需求灵活控制颜色风格。"
   ],
   "id": "76bb203c0226e649"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "# 代码5-21\n",
    "sns.palplot(sns.hls_palette(8, l=.3, s=.8))  # 生成一个包含 8 种颜色的 HLS 调色板，亮度为 0.3，饱和度为 0.8，并绘制色块"
   ],
   "id": "c9c2dfeb7a253414"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 🌈 使用 HUSL 色彩空间生成调色板\n",
    "\n",
    "本程序演示如何使用 Seaborn 中基于 HUSL（Human-friendly HSL）色彩空间生成的调色板，并以色块形式展示。主要流程如下：\n",
    "\n",
    "1. **生成 HUSL 调色板**\n",
    "   - 使用 `sns.color_palette('husl', 8)` 创建一个包含 8 种颜色的调色板；\n",
    "   - HUSL 是对 HLS 的改进版本，更符合人眼对亮度感知的均衡，适合制作高辨识度的分类配色。\n",
    "\n",
    "2. **可视化调色板**\n",
    "   - 使用 `sns.palplot()` 显示调色板，将每种颜色绘制为等宽的色块；\n",
    "   - 方便对配色方案进行直观预览与选择。\n",
    "\n",
    "这种色彩方案常用于需要颜色区分清晰但视觉友好的数据图表。"
   ],
   "id": "b737ef929dfd12d7"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T11:53:13.848517Z",
     "start_time": "2025-05-06T11:53:13.801565Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#代码5-22\n",
    "sns.palplot(sns.color_palette('husl', 8))  # 使用 HUSL 色彩空间生成 8 种颜色，并绘制为色块展示"
   ],
   "id": "bd3c4f1c2145eeb",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Figure size 576x72 with 1 Axes>"
      ],
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAcwAAABECAYAAAAMTwWHAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAAACoklEQVR4nO3av2oUURjG4W82mSiua6GNhSBq2NpKLLwJsfRGFMFCEL0OwYvwDkQb6yVqoYWNNnFCkjF7rPwTcOVrTo4uz1Oead6pfjs705VSSgAAfzVpPQAA/geCCQAJggkACYIJAAmbqy4sl8sYhiH6vo+u605yEwA0UUqJcRxjOp3GZHL8mXJlMIdhiMViUX0cAPxr5vN5zGazY2crg9n3fUREXH7xOvq9g7rLGtm5fSu6V/daz6im3Hgab3bW9/6ubz+N+5+et55RxZOLd+PBx7etZ1Tz+NK1ePh+o/WMah5dOYqdl1dbz6hm++a7uPrsXOsZVYzTZXy48/VnA3+3Mpg//obt9w5ia9ivt66x7uBz6wnVlIg4HNf3/iIiPh99bT2hmi/fxtYTqvrybb1f9Yz7W60nVLW1u74/eCLij68iffQDAAmCCQAJggkACYIJAAmCCQAJggkACYIJAAmCCQAJggkACYIJAAmCCQAJggkACYIJAAmCCQAJggkACYIJAAmCCQAJggkACYIJAAmCCQAJggkACYIJAAmCCQAJggkACYIJAAmCCQAJggkACYIJAAmCCQAJggkACYIJAAmCCQAJggkACYIJAAmCCQAJggkACYIJAAmCCQAJggkACYIJAAmCCQAJggkACYIJAAmCCQAJggkACYIJAAmCCQAJggkACYIJAAmCCQAJggkACZurLpRSIiJiPHPqxMa0UE5daD2hqq1+ve/vwsbZ1hOqOb/Zt55Q1fnN0npCVf3pw9YTqjqcHbWeUMU4XUbErwb+rit/Oo2I3d3dWCwWdZcBwD9oPp/HbDY7drYymMvlMoZhiL7vo+u6ExkIAC2VUmIcx5hOpzGZHH9ruTKYAMAvPvoBgATBBIAEwQSABMEEgITvI0pzmeG8qNIAAAAASUVORK5CYII=\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "execution_count": 15
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 🎨 使用 XKCD 命名颜色与自定义调色板\n",
    "\n",
    "本程序展示如何使用 `seaborn.xkcd_rgb` 和 `xkcd_palette()` 来绘图与展示自定义颜色。主要流程如下：\n",
    "\n",
    "1. **使用 `xkcd_rgb` 设置具体颜色绘制折线图**\n",
    "   - Seaborn 提供 XKCD 社区命名的颜色词典；\n",
    "   - 使用 `'pale red'`、`'medium green'`、`'denim blue'` 为三条线设置颜色；\n",
    "   - 使用 `lw=3` 设置线宽为 3，使线条更粗更明显；\n",
    "   - 添加图表标题并显示图形。\n",
    "\n",
    "2. **自定义定性调色板并可视化**\n",
    "   - 创建包含多个 XKCD 命名颜色的列表；\n",
    "   - 使用 `sns.xkcd_palette()` 生成调色板；\n",
    "   - 使用 `sns.palplot()` 将调色板颜色以色块形式展示。\n",
    "\n",
    "这种方式适合在需要个性化风格、增强色彩识别度的场合，尤其适合分类数据展示或演示文稿场景。"
   ],
   "id": "d7ed17994e5a1405"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T11:57:26.421382Z",
     "start_time": "2025-05-06T11:57:26.173864Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 代码5-23\n",
    "plt.plot(x, y1, sns.xkcd_rgb['pale red'], lw=3)  # 使用 XKCD 命名的浅红色绘制第一条线，线宽为3\n",
    "plt.plot(x, y2, sns.xkcd_rgb['medium green'], lw=3)  # 使用中绿色绘制第二条线\n",
    "plt.plot(x, y3, sns.xkcd_rgb['denim blue'], lw=3)  # 使用牛仔蓝色绘制第三条线\n",
    "plt.title('线条颜色示例',fontproperties=my_font)  # 设置图表标题\n",
    "plt.show()  # 显示折线图\n",
    "\n",
    "colors = ['windows blue', 'amber', 'greyish', 'faded green', 'dusty purple']  # 自定义颜色名称列表（基于 XKCD 词典）\n",
    "sns.palplot(sns.xkcd_palette(colors))  # 使用自定义颜色列表生成调色板并以色块形式展示"
   ],
   "id": "fa740a395e06d5d4",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ],
      "image/png": "[encoded data, 25236 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "<Figure size 360x72 with 1 Axes>"
      ],
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAASUAAABECAYAAADHuCM8AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAAACO0lEQVR4nO3aPW7UUBSG4eNJTBI8lqgIK5iGHokVREJKlx1RswcWQEeVKgULoKJgJCQKCqBAkUZOAJO5VPwkI5eOjybP01jybb7qledqqlJKCYAkZlMPAPifKAGpiBKQiigBqewOHazX6+i6Luq6jqqqbnMTsMVKKdH3fTRNE7PZ5nfRYJS6rovlcjnqOODuWiwW0bbtxvvBKNV1HRERL866OL/czn8NPH82j8dfT6aeMZp3D1/Fxw9vp54xivfzT3F0eBynX15PPWUUR4fHcfbyzdQzRrE/34unJ0/+NuamwSj9+cl2flni28V2RikiYu/q89QTRvWr/zn1hFFcXHXXntvocvV96gmjGroWctENpCJKQCqiBKQiSkAqogSkIkpAKqIEpCJKQCqiBKQiSkAqogSkIkpAKqIEpCJKQCqiBKQiSkAqogSkIkpAKqIEpCJKQCqiBKQiSkAqogSkIkpAKqIEpCJKQCqiBKQiSkAqogSkIkpAKqIEpCJKQCqiBKQiSkAqogSkIkpAKqIEpCJKQCqiBKQiSkAqogSkIkpAKqIEpCJKQCqiBKQiSkAqogSkIkpAKqIEpCJKQCqiBKSyO3RQSomIiAcH1a2NmcKPnUdTTxjVbn1v6gmjuL/TXHtuo4N2f+oJo9if70XEv8bcVJWBk9VqFcvlcrxlwJ22WCyibduN94NRWq/X0XVd1HUdVbXdX0vA7SmlRN/30TRNzGabN0iDUQKYgotuIBVRAlIRJSAVUQJS+Q3KWWOhCE7IdQAAAABJRU5ErkJggg==\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "execution_count": 21
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 🌗 展示连续型与离散型调色板的使用差异\n",
    "\n",
    "本程序展示了 Seaborn 中不同类型调色板的效果，包括**连续型（sequential）**、**反转调色板（_r）**、以及**离散化调色板（_d）**的应用。主要流程如下：\n",
    "\n",
    "1. **使用 `Greens` 连续型调色板**\n",
    "   - `Greens` 是一种从浅绿色到深绿色的渐变色彩方案，适合表示数量级、强度、浓度等连续变量。\n",
    "\n",
    "2. **使用 `YlOrRd_r` 反转调色板**\n",
    "   - `YlOrRd` 表示从黄色到橙色再到红色的颜色过渡；\n",
    "   - 后缀 `_r` 表示调色板被反转，即从红到黄的顺序。\n",
    "\n",
    "3. **使用 `YlOrRd_d` 离散化调色板**\n",
    "   - 后缀 `_d` 表示将连续型调色板转化为离散型调色板（适合分类变量）；\n",
    "   - 通常用于分级热力图或分段色带等分类视觉效果。\n",
    "\n",
    "通过对比三个调色板的输出，可以清晰了解它们在不同数据类型下的应用场景。"
   ],
   "id": "b6b5e9c2ea8c00fb"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T11:58:17.578127Z",
     "start_time": "2025-05-06T11:58:17.475752Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 代码5-24\n",
    "sns.palplot(sns.color_palette('Greens'))  # 显示“Greens”连续型调色板（浅绿 → 深绿）\n",
    "sns.palplot(sns.color_palette('YlOrRd_r'))  # 显示“YlOrRd”调色板的反转版本（红 → 橙 → 黄）\n",
    "sns.palplot(sns.color_palette('YlOrRd_d'))  # 显示“YlOrRd”调色板的离散版本，适合分类变量使用"
   ],
   "id": "99e18b54b7321752",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Figure size 432x72 with 1 Axes>"
      ],
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAV0AAABECAYAAAAiJuZQAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAAACV0lEQVR4nO3YMW7TYBjH4ddurKKaUCqagYE1O6dgZuwNuiIkJA6BWBEXYOQYiKl7BsQGUgsCgiWqgM0EqI284dfFPM9iyd/yn35xvqLrui4ASFGOPQDgfyK6AIlEFyCR6AIkmvUdtG0bTdNEVVVRFEXmJoB/Vtd1sdlsoq7rKMvt79re6DZNE6vVatBxAFO1XC5jPp9vve+NblVVERGxf6eOnWqatxAf36zj8+Hp2DMGs3+2iNc7r8aeMYiT92/jeHEUz05fjD1lEMeLo3h48nTsGYN5cvdB3H/5aOwZg1jsHcTze49/N/Sy3uj+ulLYqcrJRjciop21Y08Y1HnxbewJg/jSfr3wnKKz809jTxjUu+bD2BMG1XctO92aAlxBoguQSHQBEokuQCLRBUgkugCJRBcgkegCJBJdgESiC5BIdAESiS5AItEFSCS6AIlEFyCR6AIkEl2ARKILkEh0ARKJLkAi0QVIJLoAiUQXIJHoAiQSXYBEoguQSHQBEokuQCLRBUgkugCJRBcgkegCJBJdgESiC5BIdAESiS5AItEFSCS6AIlEFyCR6AIkEl2ARKILkEh0ARKJLkAi0QVIJLoAiUQXIJHoAiQSXYBEoguQSHQBEs36Drqui4iIH5s2bcwYyu/T/t3Z7a6NPWEQN8rrF55TdLh7c+wJg7pd3xp7wiAWewcR8aehlxVdz8l6vY7VajXcMoAJWy6XMZ/Pt973Rrdt22iaJqqqiqIoBh8IMAVd18Vms4m6rqMst/9J90YXgL9v2heaAFeM6AIkEl2ARKILkOgnbLNj3YY+leYAAAAASUVORK5CYII=\n"
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "<Figure size 432x72 with 1 Axes>"
      ],
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAV0AAABECAYAAAAiJuZQAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAAACYklEQVR4nO3ZvYoTURjH4XdCxgWzAb+L7TeiW3ox3oFgaaWdtZWFhbegnRejW2R7hVUXYXeQbEKOhV+wYTrPOxqfpwnMaf6B8COcaUopJQBIMRp6AMD/RHQBEokuQCLRBUg07jtYr9fRdV20bRtN02RuAvhnlVJiuVzGZDKJ0Wjzf21vdLuui/l8XnUcwLaazWYxnU43nvdGt23biIj4+uBplOOTessGdPnNi9h79HDoGdW8f/4y7rx6MvSMKpp7V+Nw/3HcPXo29JQqDvcfx0G8HnpGNe/ifhzsvR16RhXnqzaOjm//auhFvdH9eaVQjk+ifPhYZ91fYPxpe79bRMTO2eehJ1TRLL//PneWX4YdUtFOczb0hHpKxM74fOgVVfVdy3qRBpBIdAESiS5AItEFSCS6AIlEFyCR6AIkEl2ARKILkEh0ARKJLkAi0QVIJLoAiUQXIJHoAiQSXYBEoguQSHQBEokuQCLRBUgkugCJRBcgkegCJBJdgESiC5BIdAESiS5AItEFSCS6AIlEFyCR6AIkEl2ARKILkEh0ARKJLkAi0QVIJLoAiUQXIJHoAiQSXYBEoguQSHQBEokuQCLRBUgkugCJRBcgkegCJBJdgESiC5BIdAESiS5AonHfQSklIiKaW9fSxgxhdePm0BOqWuxeH3pCFU17JSIiFj8+t9Gi7A49oarF6tLQE6o4X7UR8buhFzWl5+T09DTm83m9ZQBbbDabxXQ63XjeG931eh1d10XbttE0TfWBANuglBLL5TImk0mMRps3uL3RBeDP8yINIJHoAiQSXYBEoguQ6Btyb2mBQ0NNDwAAAABJRU5ErkJggg==\n"
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "<Figure size 432x72 with 1 Axes>"
      ],
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAV0AAABECAYAAAAiJuZQAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAAACW0lEQVR4nO3ZzWrUYBiG4TdDM2DH0Vo9g0JWnkqPRcQfEMFS9y7q3gNw7cGIOQBXWrU1FBpIXPgHHbLze6PjdW0Cyeb5NjchqcZxHAOAFIu5BwD8T0QXIJHoAiQSXYBEO1MPhmGIruuiruuoqipzE8A/axzH6Ps+VqtVLBab77WT0e26Ltq2LToOYFs1TRPr9Xrj/mR067qOiIiDd69i2Z+VWzajt3fvR/PmeO4ZxbSHR3Hw8uHcM4p4/6mPi6OTuHZ8b+4pRVwcnUT77MHcM4ppnr+I108fzz2jiN29W3H46Mmvhl41Gd2fnxSW/VksLz8XGfc3WHanc08oavnlw9wTilic9j+u23m+iIh+i88WEfH19OPcE4qa+izrRxpAItEFSCS6AIlEFyCR6AIkEl2ARKILkEh0ARKJLkAi0QVIJLoAiUQXIJHoAiQSXYBEoguQSHQBEokuQCLRBUgkugCJRBcgkegCJBJdgESiC5BIdAESiS5AItEFSCS6AIlEFyCR6AIkEl2ARKILkEh0ARKJLkAi0QVIJLoAiUQXIJHoAiQSXYBEoguQSHQBEokuQCLRBUgkugCJRBcgkegCJBJdgESiC5BIdAESiS5AItEFSCS6AIl2ph6M4xgREZf1jbQxc7hc7c89oajLm3fmnlDEMPTfr/vbeb6IiHqLzxYRcX3/9twTitjduxURvxt6VTVOPDk/P4+2bcstA9hiTdPEer3euD8Z3WEYouu6qOs6qqoqPhBgG4zjGH3fx2q1isVi8wvuZHQB+PP8SANIJLoAiUQXIJHoAiT6BkjuaqBbOfZkAAAAAElFTkSuQmCC\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "execution_count": 22
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 🌈 使用 Cubehelix 生成连续调色板并应用于密度图\n",
    "\n",
    "本程序演示了如何使用 `cubehelix_palette()` 创建可用于连续变量的调色板，并将其应用于核密度估计（KDE）图。主要流程如下：\n",
    "\n",
    "1. **创建 Cubehelix 调色板预览**\n",
    "   - 使用 `sns.cubehelix_palette(8, start=1, rot=0)` 生成包含 8 种颜色的 Cubehelix 调色板；\n",
    "   - `start=1` 控制颜色循环的起点（影响色调），`rot=0` 表示无色调旋转；\n",
    "   - 使用 `sns.palplot()` 可视化调色板色块。\n",
    "\n",
    "2. **生成二维正态分布模拟数据**\n",
    "   - 使用 `np.random.multivariate_normal()` 生成 300 个具有负相关的二维随机点 `(x, y)`。\n",
    "\n",
    "3. **生成可连续使用的调色板对象**\n",
    "   - 设置 `as_cmap=True` 将调色板转换为 `matplotlib` 可识别的颜色映射（cmap），适合用于等高线或热力图。\n",
    "\n",
    "4. **绘制 KDE 密度图并应用 cmap**\n",
    "   - 使用 `sns.kdeplot()` 以 `x` 和 `y` 为输入，绘制二维核密度图；\n",
    "   - 设置 `cmap` 应用自定义色带，`shade=True` 填充轮廓区域；\n",
    "   - 添加图表标题并展示图形。\n",
    "\n",
    "该方法适用于连续型变量可视化，常用于热力图、地理密度图等图表。"
   ],
   "id": "2df9d460c0b09d3f"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T11:59:07.723588Z",
     "start_time": "2025-05-06T11:59:07.567662Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 代码5-25\n",
    "sns.palplot(sns.cubehelix_palette(8, start=1, rot=0))  # 显示 Cubehelix 调色板（起点色调为1，无旋转）\n",
    "x, y = np.random.multivariate_normal([0, 0], [[1, -.5], [-.5, 1]], size=300).T  # 生成二维正态分布数据，包含负相关\n",
    "\n",
    "cmap = sns.cubehelix_palette(as_cmap=True)  # 将 Cubehelix 调色板转换为可连续使用的 cmap 对象\n",
    "sns.kdeplot(x, y, cmap=cmap, shade=True)  # 绘制二维 KDE 密度图，应用连续颜色映射并填充阴影\n",
    "plt.title('连续调色板')  # 设置图表标题\n",
    "plt.show()  # 显示图形"
   ],
   "id": "b70226ddf72d2691",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Figure size 576x72 with 1 Axes>"
      ],
      "image/png": "[encoded data, 5528 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "execution_count": 24
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 🎨 使用 light_palette 和 dark_palette 创建连续调色板\n",
    "\n",
    "本程序演示了如何通过 Seaborn 提供的 `light_palette()` 和 `dark_palette()` 方法创建基于特定颜色的渐变调色板，并将其应用于密度图。主要流程如下：\n",
    "\n",
    "1. **使用 `light_palette` 创建亮色系渐变调色板**\n",
    "   - 以 `'blue'` 为基色生成从浅到深的蓝色渐变；\n",
    "   - 适合用于连续数据或表示低强度数值。\n",
    "\n",
    "2. **使用 `dark_palette` 创建暗色系渐变调色板**\n",
    "   - 以 `'yellow'` 为基色生成从深到浅的黄色渐变；\n",
    "   - 常用于突出高数值或高浓度区域。\n",
    "\n",
    "3. **基于 HUSL 空间自定义调色板并作为 cmap 使用**\n",
    "   - 使用 `(200, 80, 60)` 的 HUSL 色值作为种子色；\n",
    "   - 参数说明：\n",
    "     - `input='husl'`：输入使用 HUSL 色彩空间；\n",
    "     - `reverse=True`：颜色顺序反转；\n",
    "     - `as_cmap=True`：输出为可用于热力图或密度图的连续 colormap。\n",
    "\n",
    "4. **应用自定义 cmap 到 KDE 密度图**\n",
    "   - 使用 `sns.kdeplot()` 绘制二维核密度估计图；\n",
    "   - 应用自定义色带并显示图表。\n",
    "\n",
    "该方法适用于需要根据特定品牌色、设计语言进行可视化风格定制的场景。"
   ],
   "id": "178c637799a9b81b"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T12:00:58.173974Z",
     "start_time": "2025-05-06T12:00:58.020020Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 代码5-26\n",
    "sns.palplot(sns.light_palette('blue'))  # 创建以 blue 为基色的亮色渐变调色板，并以色块形式展示\n",
    "sns.palplot(sns.dark_palette('yellow'))  # 创建以 yellow 为基色的暗色渐变调色板并展示\n",
    "# 创建以 HUSL 色值为种子色的暗色调色板，反转顺序，作为 cmap 使用\n",
    "pal = sns.dark_palette((200, 80, 60), input='husl', reverse=True, as_cmap=True)\n",
    "sns.kdeplot(x, y, cmap=pal)  # 绘制 KDE 密度图，应用自定义 cmap 色带\n",
    "plt.title('自定义连续调色板')  # 设置图标题\n",
    "plt.show()  # 显示图形"
   ],
   "id": "8cec42a4620de6a6",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Figure size 432x72 with 1 Axes>"
      ],
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAV0AAABECAYAAAAiJuZQAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAAACTElEQVR4nO3ZMWrbYBjH4VeO1QxCU8AQ0q3UtNCr5Aw+Rs6QQ2TIebKnQVBKpkyZjIbEwV+HJh1itFWvqPo8i8DC8P/A/DBSVUopAUCKxdQDAP4noguQSHQBEokuQKLl0I39fh9930dd11FVVeYmgH9WKSV2u100TROLxeH/2sHo9n0fXdeNOg5grtbrdbRte/D5YHTruo6IiLOzj7Fc1uMtm9D9/c/o+09TzxhN0/yIm5vPU88Yxe3tUWw2d3F9/WXqKaPYbO7i4uLr1DNGc3n5Pc7Pv009YxSr1XNcXXV/GvreYHTfHiksl/Xgl+eglA9TTxjV09M8z7fdHr1e53m+iIjHx+OpJ4zq4WHe5xt6LOtFGkAi0QVIJLoAiUQXIJHoAiQSXYBEoguQSHQBEokuQCLRBUgkugCJRBcgkegCJBJdgESiC5BIdAESiS5AItEFSCS6AIlEFyCR6AIkEl2ARKILkEh0ARKJLkAi0QVIJLoAiUQXIJHoAiQSXYBEoguQSHQBEokuQCLRBUgkugCJRBcgkegCJBJdgESiC5BIdAESiS5AItEFSCS6AIlEFyCR6AIkEl2ARKILkEh0ARKJLkAi0QVIJLoAiZZDN0opERHx8rJLGzOFqnqeesKojo/neb62PXq9zvN8EREnJ09TTxjV6ek8z7da/f5NvjX0vaoM3Nlut9F13XjLAGZsvV5H27YHnw9Gd7/fR9/3Udd1VFU1+kCAOSilxG63i6ZpYrE4fII7GF0A/j4v0gASiS5AItEFSCS6AIl+Ad7xZN5NJ6PBAAAAAElFTkSuQmCC\n"
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "<Figure size 432x72 with 1 Axes>"
      ],
      "image/png": "[encoded data, 20144 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "execution_count": 25
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 🔄 使用分级调色板（diverging palette）可视化中性到极端值的配色\n",
    "\n",
    "本程序演示了如何使用 Seaborn 的分级（diverging）调色板来表现中心对称型数据（如偏差、变化程度等）。主要流程如下：\n",
    "\n",
    "1. **使用 `BrBG` 分级调色板**\n",
    "   - “棕-绿”色系，从棕色过渡到绿色，中间带有中性色，适合表现正负变化或上下偏离。\n",
    "\n",
    "2. **使用 `RdBu_r` 分级调色板（反转）**\n",
    "   - “红-蓝”调色板，原版是红 → 白 → 蓝；\n",
    "   - 使用 `_r` 表示反转方向：蓝 → 白 → 红；\n",
    "   - 常用于热图或残差图等有正负对称意义的图表。\n",
    "\n",
    "3. **使用 `sns.palplot()` 进行调色板可视化**\n",
    "   - 将颜色按顺序展示为一行色块，便于选择与对比。\n",
    "\n",
    "这些调色板适用于表示“零值为中心、两端对称”的数据场景，如偏差、增长率、温度变化等。"
   ],
   "id": "e929c1a879ddee9d"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "# 代码5-27\n",
    "sns.palplot(sns.color_palette('BrBG', 7))  # 显示“BrBG”分级调色板（棕 → 中性 → 绿，7色）\n",
    "sns.palplot(sns.color_palette('RdBu_r', 7))  # 显示“RdBu”调色板的反转版本（蓝 → 白 → 红，7色）"
   ],
   "id": "83d8fb58fe5c5072"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 🌡️ 使用 `coolwarm` 分级调色板进行可视化\n",
    "\n",
    "本程序演示如何使用 `coolwarm` 分级调色板，并将其以色块形式展示。主要流程如下：\n",
    "\n",
    "1. **加载 `coolwarm` 分级调色板**\n",
    "   - `coolwarm` 是一种经典的中心对称型调色板，颜色从冷色（蓝）过渡到暖色（红）；\n",
    "   - 中间为浅灰白色，常用于表示正负变化、残差、偏离等具有中心值的数据。\n",
    "\n",
    "2. **设置颜色数量并可视化**\n",
    "   - 通过 `sns.color_palette('coolwarm', 7)` 设置调色板颜色数为 7；\n",
    "   - 使用 `sns.palplot()` 将颜色以色块形式展示，便于查看和选配。\n",
    "\n",
    "该调色板非常适合用于表示“高低、正负”对称型指标，广泛用于热力图、残差图等可视化图表。"
   ],
   "id": "869c987e01c254e0"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T12:02:14.615703Z",
     "start_time": "2025-05-06T12:02:14.550694Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 代码5-28\n",
    "sns.palplot(sns.color_palette('coolwarm', 7))  # 显示 coolwarm 分级调色板（蓝 → 白 → 红，7色）"
   ],
   "id": "72ea8a1224881612",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Figure size 504x72 with 1 Axes>"
      ],
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAZQAAABECAYAAACmjMM7AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAAACf0lEQVR4nO3ZPW4TURSG4TNOJolwHCEKCiSaFC4oqGkpWQAtDQtiCayAmiVATUHhIg1SSoSwBpI4nqHiJyhTIM71TaznKe+4+AqPXtm3GYZhCAD4T5PaAwDYDoICQApBASCFoACQYnfsQd/30XVdtG0bTdNschMAN9QwDLFarWI6ncZkcvU3yWhQuq6LxWJRfBwAt898Po/ZbHblbDQobdtGRMSbd/ejOxv92K324ulpvD99VHtGMU8efIzPk3ntGcXc6xdx9NcXelt8XS7j+OxT7RnFnBw8jOMPb2vPKObk8bOYvX5Ve0YR/eFRdM9f/mrEn0ZL8fNvru5sN5bftzMoERHn6/3aE4rqm73aE4ra2dnea8C94bL2hKLai2+1JxS1s/xSe0JR112FbO/bCMBGCQoAKQQFgBSCAkAKQQEghaAAkEJQAEghKACkEBQAUggKACkEBYAUggJACkEBIIWgAJBCUABIISgApBAUAFIICgApBAWAFIICQApBASCFoACQQlAASCEoAKQQFABSCAoAKQQFgBSCAkAKQQEghaAAkEJQAEghKACkEBQAUggKACkEBYAUggJACkEBIIWgAJBCUABIISgApBAUAFIICgApBAWAFIICQApBASCFoACQQlAASCEoAKQQFABSCAoAKQQFgBS7Yw+GYYiIiOnB5cbG1LC/c157QlGT4aL2hKLW6772hGIumtHXcyus9u7UnlDUena39oQi+sOjiPjdiD81w3WnEbFcLmOxWJRdBsCtNJ/PYzabXTkbDUrf99F1XbRtG03TbGQgADfbMAyxWq1iOp3GZHL11mQ0KADwL1zKA5BCUABIISgApBAUAFL8AE6waqlTtU14AAAAAElFTkSuQmCC\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "execution_count": 26
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 🔄 使用 `diverging_palette()` 构造自定义分级调色板\n",
    "\n",
    "本程序演示了如何通过 `sns.diverging_palette()` 自定义生成分级调色板，并进行可视化。主要流程如下：\n",
    "\n",
    "1. **基础使用：生成默认的分级调色板**\n",
    "   - 通过设置两个色相角（如 240 到 10），在 HSV 色轮上生成对称配色；\n",
    "   - 常用于表达“中心为 0，正负方向对称”的数据。\n",
    "\n",
    "2. **自定义亮度与饱和度**\n",
    "   - 使用参数 `s=80` 控制饱和度，`l=55` 控制亮度；\n",
    "   - 色彩更加平衡、柔和。\n",
    "\n",
    "3. **指定 `center='dark'` 生成深色中间调色板**\n",
    "   - 默认中间为浅色（白色），设置为 `dark` 后中间色加深，适用于深色背景或高对比视觉需求。\n",
    "\n",
    "4. **使用 `sep` 参数控制渐变间隔**\n",
    "   - `sep=80` 表示将中间“中性色”区域拉宽，使调色板两端色块过渡更缓。\n",
    "\n",
    "这些方法适用于定制高质量热力图、差异图和对称偏移型数据的视觉呈现。"
   ],
   "id": "652a1f3f13f9e469"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T12:04:13.579370Z",
     "start_time": "2025-05-06T12:04:13.435142Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 代码5-29\n",
    "sns.palplot(sns.diverging_palette(240, 10, n=7))  # 生成默认的蓝-红型分级调色板（7种颜色）\n",
    "sns.palplot(sns.diverging_palette(150, 275, s=80, l=55, n=7))  # 自定义色相、饱和度和亮度的绿色-紫色分级调色板\n",
    "sns.palplot(sns.diverging_palette(250, 15, s=75, l=40, n=7, center='dark'))  # 生成以暗色为中心的调色板，适合深色背景\n",
    "sns.palplot(sns.diverging_palette(150, 275, s=80, l=55, n=7, sep=80))  # 使用 sep 参数控制中间区域宽度，使渐变更平滑"
   ],
   "id": "44edf0734b6df13",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Figure size 504x72 with 1 Axes>"
      ],
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAZQAAABECAYAAACmjMM7AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAAACe0lEQVR4nO3bvWoUYRiG4Xc2GdAMG0PQxiop3DNRLDwQS2sra3vPxEKw8zDWwoBgo0RDmCQwyYyVP4EMKL5fxgzXVc5s8RTL3vPDVsMwDAEA/2gx9QAA5kFQAEghKACkEBQAUmyOnej7Ptq2jbquo6qq69wEwH9qGIboui6aponF4vI9yWhQ2raN9XpdfBwAN89qtYrlcnnp2GhQ6rqOiIhX7z7G0dl52WUTef5oP968b6eeUczjB0186ZupZxRzd9HG/t7e1DOK+HBwEPc/H049o5hP93Zj9/XbqWcUc/jkYTQvXk49o4h+ZztOnz392YjfjQblx2Ouo7Pz+Hoyz6BERJx08/4bTj/z12RXfannYvOin3pCURsnp1NPKGpx+G3qCUVd9Spk3r82AFwbQQEghaAAkEJQAEghKACkEBQAUggKACkEBYAUggJACkEBIIWgAJBCUABIISgApBAUAFIICgApBAWAFIICQApBASCFoACQQlAASCEoAKQQFABSCAoAKQQFgBSCAkAKQQEghaAAkEJQAEghKACkEBQAUggKACkEBYAUggJACkEBIIWgAJBCUABIISgApBAUAFIICgApBAWAFIICQApBASCFoACQQlAASCEoAKQQFABSCAoAKQQFgBSCAkAKQQEghaAAkGJz7MQwDBERcefW6EdmYauupp5Q1CL6qScU1XXd1BOKOd+Y9/XexdbtqScU1e/uTD2hiH5nOyJ+NeJ31XDV0Yg4Pj6O9XpddhkAN9JqtYrlcnnp2GhQ+r6Ptm2jruuoqnlfxQPwZ4ZhiK7rommaWCwu30WPBgUA/sa8H9ICcG0EBYAUggJACkEBIMV341VroDOnIvwAAAAASUVORK5CYII=\n"
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "<Figure size 504x72 with 1 Axes>"
      ],
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAZQAAABECAYAAACmjMM7AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAAACeElEQVR4nO3bMWsTcRzH4d+lvRR6BFxEHYS6ZLODL0Nw8wX5EnwhboLvwqU4ZbHgYF1KoVyhOZO/k9pADxR/17PH84x3y/cPIZ8kR6pSSgkA+EezsQcAMA2CAkAKQQEghaAAkGK/78Z2u422baOu66iq6i43AfCfKqVE13XRNE3MZrvfSXqD0rZtrFarwccBcP8sl8tYLBY713qDUtd1RES8/fQhLtZXwy4byZsXr+P9t5OxZwzm1aPjOJtfjz1jMI/XB3F09GzsGYM4Pf0c9fXTsWcMpjv4EmcnT8aeMZjHx1/j47uHY88YxPxwE89fnv9qxE29Qfn5M9fF+irOr9vh1o2s3azHnjCoTTXtvxnd9qKeiiqme7aIiM269+1nEq7baZ/vtkchHsoDkEJQAEghKACkEBQAUggKACkEBYAUggJACkEBIIWgAJBCUABIISgApBAUAFIICgApBAWAFIICQApBASCFoACQQlAASCEoAKQQFABSCAoAKQQFgBSCAkAKQQEghaAAkEJQAEghKACkEBQAUggKACkEBYAUggJACkEBIIWgAJBCUABIISgApBAUAFIICgApBAWAFIICQApBASCFoACQQlAASCEoAKQQFABSCAoAKQQFgBSCAkAKQQEghaAAkEJQAEghKACk2O+7UUqJiIgH88M7GzOGZm8+9oRB7ZVq7AmD6rpu7AmDKTHds0VE7M2/jz1hUAfNNM83P9xExO9G3FSV265GxOXlZaxWq2GXAXAvLZfLWCwWO9d6g7LdbqNt26jrOqpq2p9yAfgzpZToui6aponZbPepSW9QAOBveCgPQApBASCFoACQQlAASPEDk+prjEA2OIEAAAAASUVORK5CYII=\n"
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "<Figure size 504x72 with 1 Axes>"
      ],
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAZQAAABECAYAAACmjMM7AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAAACh0lEQVR4nO3ZT2pTURjG4S8hV5AYrTUdOs3cPbgAl+BUCmpVRBAdCIIoWBXETThwAW7DSSYuwFaq7UUwkuvIP4FmIH6npw3PM7yXwHtGP25Or+u6LgDgP/VrDwBgNQgKACkEBYAUggJAisGyF/P5PNq2jaZpotfrHeUmAI6prutiNpvFcDiMfn/xm2RpUNq2jel0WnwcACfPZDKJ0Wi08GxpUJqmiYiIZ28/xN7B97LLKnl89VLcffGu9oxint68ElsPX9SeUcz2o5txY3Oz9owiXr5+HW9uXa89o5hrz1/F+3tbtWcUc/nJdnx8cKf2jCIGa+fj4u37vxux8G7Zj379zbV38D1291czKBERu3tt7QlF7Xz+UntCUTufPtWeUMzXnZ3aE4r6trva5/vxebXPd9hViEt5AFIICgApBAWAFIICQApBASCFoACQQlAASCEoAKQQFABSCAoAKQQFgBSCAkAKQQEghaAAkEJQAEghKACkEBQAUggKACkEBYAUggJACkEBIIWgAJBCUABIISgApBAUAFIICgApBAWAFIICQApBASCFoACQQlAASCEoAKQQFABSCAoAKQQFgBSCAkAKQQEghaAAkEJQAEghKACkEBQAUggKACkEBYAUggJACkEBIIWgAJBCUABIISgApBAUAFIICgApBAWAFINlL7qui4iItTOnjmxMDRfWhrUnFDVeP1d7QlHjjY3aE4o5Ox7XnlDU6Qurfb7B+mqeb7B2PiL+NOJvve6wpxGxv78f0+m07DIATqTJZBKj0Wjh2dKgzOfzaNs2mqaJXq93JAMBON66rovZbBbD4TD6/cVbk6VBAYB/4VIegBSCAkAKQQEghaAAkOInCMtqolSIZCQAAAAASUVORK5CYII=\n"
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "<Figure size 504x72 with 1 Axes>"
      ],
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAZQAAABECAYAAACmjMM7AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAAACb0lEQVR4nO3ZMW7TYBjH4ddR3EqxIrEgBqhQl2wsDByCmQNxBA7CzCGQ2JiyRKjtwFJVqlypdZqPCWikekC8rlvreUZ7+X+JpZ8SV6WUEgDwn2ZjDwBgGgQFgBSCAkAKQQEgxbzvxm63i7Zto67rqKrqITcB8EiVUqLrumiaJmaz/d8kvUFp2zbW6/Xg4wB4elarVSyXy71rvUGp6zoiIj59/xIXN1fDLhvJx7cf4uvVydgzBvNucRQvXr8ce8Zgfv44i+Pj47FnDGKz2cTRq2meLSLi5HQT7el0n83m1Vl8+/x87BmDOFjcxpv3538acVdvUH7/zXVxcxXn1+1w60Z2XbZjTxjUvO79iifhvod6KqZ8toiIsp32s3ndTvt8970K8VIegBSCAkAKQQEghaAAkEJQAEghKACkEBQAUggKACkEBYAUggJACkEBIIWgAJBCUABIISgApBAUAFIICgApBAWAFIICQApBASCFoACQQlAASCEoAKQQFABSCAoAKQQFgBSCAkAKQQEghaAAkEJQAEghKACkEBQAUggKACkEBYAUggJACkEBIIWgAJBCUABIISgApBAUAFIICgApBAWAFIICQApBASCFoACQQlAASCEoAKQQFABSCAoAKQQFgBSCAkAKQQEgxbzvRiklIiKeHSwebMwYDqvej2AStt127AmD6rpu7AmDmfLZIiKq+bSfzcNmmuc7WNxGxN9G3FWV+65GxOXlZazX62GXAfAkrVarWC6Xe9d6g7Lb7aJt26jrOqqqepCBADxupZToui6aponZbP+tSW9QAOBfeCkPQApBASCFoACQQlAASPELNnZsjOHjtVgAAAAASUVORK5CYII=\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "execution_count": 27
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 🎨 设置 Seaborn 调色板的多种方式\n",
    "\n",
    "本程序展示了 Seaborn 中控制绘图颜色的三种方法，包括默认调色板、全局设置、以及临时设置调色板的用法。主要流程如下：\n",
    "\n",
    "1. **使用默认调色板绘图**\n",
    "   - 调用自定义函数 `showLine()` 绘制三条线；\n",
    "   - 未手动设置调色板，使用的是 Seaborn 默认调色方案。\n",
    "\n",
    "2. **使用 `sns.set_palette()` 全局设置调色板**\n",
    "   - 设置全局调色板为 `'YlOrRd_d'`（黄色到红色的离散色带）；\n",
    "   - 后续所有绘图默认采用此调色板，直到下次更改或重置。\n",
    "\n",
    "3. **恢复默认配置并设置中文字体**\n",
    "   - 使用 `sns.set()` 恢复所有默认 Seaborn 设置；\n",
    "   - 配置 Matplotlib 中文字体与负号正常显示。\n",
    "\n",
    "4. **使用 `with sns.color_palette(...)` 临时设置调色板**\n",
    "   - 在 `with` 语句块内应用 `'PuBuGn_d'`（蓝绿色渐变）作为临时调色板；\n",
    "   - 块内图形使用该调色板，块外自动恢复默认；\n",
    "   - 用于对比同一数据下不同配色方案的视觉差异。\n",
    "\n",
    "这种灵活的调色板设置方式便于在报告或多图展示中统一或强调配色。"
   ],
   "id": "4c9c4f2247acc604"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T12:05:28.020472Z",
     "start_time": "2025-05-06T12:05:27.661681Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 代码5-30\n",
    "x = np.arange(1, 10, 2)  # 创建横轴数据\n",
    "y1 = x + 1  # 第1条折线的y轴数据\n",
    "y2 = x + 3  # 第2条折线的y轴数据\n",
    "y3 = x + 5  # 第3条折线的y轴数据\n",
    "\n",
    "def showLine(flip=1):  # 封装绘图函数\n",
    "    sns.lineplot(x, y1)\n",
    "    sns.lineplot(x, y2)\n",
    "    sns.lineplot(x, y3)\n",
    "\n",
    "mpl.rcParams['font.family'] = my_font.get_name()\n",
    "\n",
    "showLine()  # 使用默认调色板绘图\n",
    "plt.title('默认调色板')\n",
    "plt.show()\n",
    "\n",
    "sns.set_palette('YlOrRd_d')  # 设置全局调色板为“黄色-红色”渐变（离散）\n",
    "showLine()\n",
    "plt.title('使用set_palette设置调色板')\n",
    "plt.show()\n",
    "\n",
    "sns.set()  # 恢复所有默认设置\n",
    "# 重设代码字体\n",
    "mpl.rcParams['font.family'] = my_font.get_name()\n",
    "\n",
    "pic = plt.figure(figsize=(8, 4))  # 创建画布，设置尺寸\n",
    "\n",
    "with sns.color_palette('PuBuGn_d'):  # 临时设置调色板为蓝绿色离散色带\n",
    "    pic.add_subplot(1, 2, 1)\n",
    "    showLine()\n",
    "    plt.title('使用color_palette设置调色板')\n",
    "\n",
    "pic.add_subplot(1, 2, 2)  # 块外恢复默认调色板\n",
    "showLine()\n",
    "plt.title('默认调色板')\n",
    "\n",
    "plt.show()"
   ],
   "id": "1bf2c74159cd951d",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ],
      "image/png": "[encoded data, 23464 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ],
      "image/png": "[encoded data, 25056 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "<Figure size 576x288 with 2 Axes>"
      ],
      "image/png": "[encoded data, 23200 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "execution_count": 31
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 🔥 使用热力图展示特征之间的相关性\n",
    "\n",
    "本程序用于加载波士顿房价数据，并使用 Seaborn 的热力图（heatmap）展示各特征之间的相关系数矩阵。主要流程如下：\n",
    "\n",
    "1. **加载数据集**\n",
    "   - 读取本地的 `boston_house_prices.csv` 文件，使用 `encoding='gbk'` 支持中文列名；\n",
    "   - 数据包含多个与房价相关的变量。\n",
    "\n",
    "2. **计算特征相关系数矩阵**\n",
    "   - 使用 `DataFrame.corr()` 方法计算所有数值型特征两两之间的皮尔逊相关系数；\n",
    "   - 输出为对称矩阵，值范围为 [-1, 1]。\n",
    "\n",
    "3. **绘制热力图**\n",
    "   - 使用 `sns.heatmap()` 生成颜色编码的相关性矩阵图；\n",
    "   - 深色表示强相关，浅色表示弱相关，便于发现变量之间的关系模式。\n",
    "\n",
    "4. **显示图表**\n",
    "   - 设置标题为“特征矩阵热力图”，使用 `plt.show()` 渲染图形。\n",
    "\n",
    "热力图是探索多变量数据结构和变量间关系的常用工具。"
   ],
   "id": "ee4e1e9b752fad83"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T12:06:24.089076Z",
     "start_time": "2025-05-06T12:06:23.654046Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 代码5-31\n",
    "boston = pd.read_csv('./data/boston_house_prices.csv', encoding='gbk')  # 读取波士顿房价数据，支持中文列名\n",
    "plt.rcParams['axes.unicode_minus'] = False  # 显示负号正常\n",
    "corr = boston.corr()  # 计算各特征之间的相关系数矩阵\n",
    "sns.heatmap(corr)  # 使用 Seaborn 绘制热力图展示相关性\n",
    "plt.title('特征矩阵热力图')  # 设置图表标题\n",
    "plt.show()  # 显示图表"
   ],
   "id": "5ca6dbaa7745b65c",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Figure size 432x288 with 2 Axes>"
      ],
      "image/png": "[encoded data, 59744 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "execution_count": 32
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 🧊 显示带数值标签的特征相关性热力图\n",
    "\n",
    "本程序基于已有的相关系数矩阵，绘制更清晰、带有具体数值标注的热力图，方便进一步分析变量间的关系强度。主要流程如下：\n",
    "\n",
    "1. **设置图像尺寸**\n",
    "   - 使用 `plt.figure(figsize=(10, 10))` 设置图表画布大小为 10x10 英寸，避免图像拥挤。\n",
    "\n",
    "2. **绘制带注释的热力图**\n",
    "   - `sns.heatmap()` 添加参数：\n",
    "     - `annot=True` 表示在每个单元格内显示数值；\n",
    "     - `fmt='.2f'` 控制注释保留两位小数，提升可读性。\n",
    "\n",
    "3. **设置标题并展示图形**\n",
    "   - 使用 `plt.title()` 添加标题；\n",
    "   - 使用 `plt.show()` 显示图像。\n",
    "\n",
    "这种热力图适合用于报告、课件、数据分析文档中，帮助读者更精确理解变量间关系。"
   ],
   "id": "35d777703bc62483"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T12:07:13.829620Z",
     "start_time": "2025-05-06T12:07:13.270370Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 代码5-32\n",
    "plt.figure(figsize=(10, 10))  # 设置图像尺寸为10x10英寸，避免标签重叠\n",
    "sns.heatmap(corr, annot=True, fmt='.2f')  # 绘制相关系数热力图，annot显示数值，fmt保留两位小数\n",
    "plt.title('特征矩阵热力图')  # 设置图表标题\n",
    "plt.show()  # 显示图表"
   ],
   "id": "c3471e8d78c38c3",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Figure size 720x720 with 2 Axes>"
      ],
      "image/png": "[encoded data, 178656 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "execution_count": 33
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 📌 使用 Stripplot 绘制销售部离职员工的工作时长分布\n",
    "\n",
    "本程序提取销售部门中已离职员工的数据，并使用 Seaborn 的 Stripplot（分布散点图）展示其“每月平均工作小时数”的离散分布情况。主要流程如下：\n",
    "\n",
    "1. **筛选特定员工子集**\n",
    "   - 从 `hr` 数据集中提取：\n",
    "     - 部门为“销售部”；\n",
    "     - 离职状态为 1（表示已离职）的记录；\n",
    "   - 得到 `sale` 子集数据，用于后续分析。\n",
    "\n",
    "2. **绘制 stripplot 水平散点图**\n",
    "   - 使用 `sns.stripplot()` 绘制水平方向的分布图；\n",
    "   - 每个点代表一个员工，X 轴表示其每月平均工作小时数；\n",
    "   - 用于展示单变量的离散分布特征。\n",
    "\n",
    "3. **设置图表标题并显示图形**\n",
    "   - 图表标题为“简单水平分布散点图”，使用 `plt.show()` 呈现图像。\n",
    "\n",
    "该图适合用于观察单一变量在某一人群中的集中趋势和离散情况。"
   ],
   "id": "d243f07ea4c0c3cf"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T12:07:57.833571Z",
     "start_time": "2025-05-06T12:07:57.747277Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 代码5-33\n",
    "# 提取部门为销售部、离职为1的数据\n",
    "sale = hr.iloc[(hr['部门'].values=='销售部') & (hr['离职'].values==1), :]  # 提取“销售部”且已离职的员工数据子集\n",
    "sns.stripplot(x=sale['每月平均工作小时数（小时）'])  # 绘制工作时长的水平分布散点图\n",
    "plt.title('简单水平分布散点图')  # 设置图表标题\n",
    "plt.show()  # 显示图表"
   ],
   "id": "7591a9fd351482c",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ],
      "image/png": "[encoded data, 27232 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "execution_count": 34
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 🎯 比较 Stripplot 的默认随机抖动与无抖动效果\n",
    "\n",
    "本程序从 HR 数据中提取所有已离职员工，绘制两个 Stripplot 图，比较默认带随机抖动与不带抖动的区别。主要流程如下：\n",
    "\n",
    "1. **提取离职员工子集**\n",
    "   - 从数据集中筛选出 `离职 == 1` 的记录，得到变量 `hr1`；\n",
    "   - 这部分数据用于后续工作时长与部门的可视化分析。\n",
    "\n",
    "2. **创建图像画布并设置布局**\n",
    "   - 使用 `plt.figure()` 设置画布大小；\n",
    "   - 使用 `plt.subplot(121)` 和 `plt.subplot(122)` 创建两个子图进行并列比较。\n",
    "\n",
    "3. **绘制第一个 Stripplot（默认带抖动）**\n",
    "   - 使用 `sns.stripplot()` 按“部门”分组绘制每月工作时长；\n",
    "   - 默认启用 `jitter=True` 添加水平抖动，防止数据点重叠；\n",
    "   - 适合数据密集或离散值重复度高的情况。\n",
    "\n",
    "4. **绘制第二个 Stripplot（无抖动）**\n",
    "   - 设置 `jitter=False` 关闭抖动，所有点严格垂直对齐；\n",
    "   - 用于强调具体数值位置或比较密度。\n",
    "\n",
    "5. **设置标题与刻度显示**\n",
    "   - 设置 X 轴刻度角度为 70°，防止文字重叠；\n",
    "   - 添加图表标题以对比不同抖动模式。\n",
    "\n",
    "该示例有助于理解 Stripplot 中 jitter 参数的视觉效果差异。"
   ],
   "id": "a5a1d8a7af0db413"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T12:08:43.497160Z",
     "start_time": "2025-05-06T12:08:43.223190Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 代码5-34\n",
    "hr1 = hr.iloc[hr['离职'].values==1, :]  # 提取所有已离职员工的数据\n",
    "plt.figure(figsize=(10, 5))  # 设置画布大小为10x5英寸\n",
    "\n",
    "plt.subplot(121)  # 创建第一个子图（左侧）\n",
    "plt.xticks(rotation=70)  # X轴标签旋转70度，防止部门名重叠\n",
    "sns.stripplot(x='部门', y='每月平均工作小时数（小时）', data=hr1)  # 默认启用随机抖动，展示散点分布\n",
    "plt.title('默认随机噪声抖动')  # 设置子图标题\n",
    "\n",
    "plt.subplot(122)  # 创建第二个子图（右侧）\n",
    "plt.xticks(rotation=70)\n",
    "sns.stripplot(x='部门', y='每月平均工作小时数（小时）', data=hr1, jitter=False)  # 禁用抖动，点严格对齐\n",
    "plt.title('无随机噪声抖动')  # 设置子图标题\n",
    "\n",
    "plt.show()  # 显示两个子图"
   ],
   "id": "817c77a2fb3d1689",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Figure size 720x360 with 2 Axes>"
      ],
      "image/png": "[encoded data, 89248 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "execution_count": 37
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 💼 高薪在职员工的晋升与工作时长可视化\n",
    "\n",
    "本程序筛选出薪资为“高”且仍在职的员工，使用带颜色区分的 Stripplot（分布散点图）展示他们在“5年内是否晋升”与“平均每月工作小时数”之间的关系。主要流程如下：\n",
    "\n",
    "1. **筛选高薪在职员工子集**\n",
    "   - 条件为：\n",
    "     - `薪资 == '高'`；\n",
    "     - `离职 == 0`（表示仍在职）；\n",
    "   - 得到变量 `hr2`，用于后续分析。\n",
    "\n",
    "2. **绘制 Stripplot 分布图**\n",
    "   - 使用 `x='5年内升职'` 表示是否晋升；\n",
    "   - `y='每月平均工作小时数（小时）'` 表示工作负荷；\n",
    "   - `hue='部门'` 用颜色区分不同部门；\n",
    "   - `jitter=True` 添加水平抖动，防止数据点重叠。\n",
    "\n",
    "3. **设置图表标题并显示图形**\n",
    "   - 图标题为“前5年是否晋升与平均每月工作时长”；\n",
    "   - 使用 `plt.show()` 显示图表。\n",
    "\n",
    "该图表用于揭示不同部门员工在是否晋升前提下的工作时长分布特征。"
   ],
   "id": "cab573a1440c41d2"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T12:09:17.837162Z",
     "start_time": "2025-05-06T12:09:17.618197Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 代码5-35\n",
    "# 提取高薪在职的数据\n",
    "hr2 = hr.iloc[(hr['薪资'].values=='高') & (hr['离职'].values==0), :]  # 筛选高薪且仍在职的员工数据\n",
    "sns.stripplot(x='5年内升职', y='每月平均工作小时数（小时）', hue='部门', data=hr2, jitter=True)  # 绘制按部门分类的工作时长散点图\n",
    "plt.title('前5年是否晋升与平均每月工作时长')  # 设置图表标题\n",
    "plt.show()  # 显示图形"
   ],
   "id": "d37c76293fec14d6",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ],
      "image/png": "[encoded data, 65716 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "execution_count": 39
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 📊 比较分组堆叠与分离显示效果的 Stripplot 图\n",
    "\n",
    "本程序基于高薪在职员工（`hr2`），绘制两个分布散点图（Stripplot），用于对比同组堆叠（默认）与横向分离（`dodge=True`）的效果。主要流程如下：\n",
    "\n",
    "1. **设置图像布局**\n",
    "   - 使用 `plt.figure(figsize=(10, 13))` 设置图表高度更大的画布；\n",
    "   - 创建两个子图用于上下对比展示。\n",
    "\n",
    "2. **绘制第一个 Stripplot（默认叠加）**\n",
    "   - 根据“部门”分组、以“是否在5年内晋升”为颜色区分；\n",
    "   - 多个类别的数据点默认重叠在同一位置；\n",
    "   - 用于查看整体密度，但颜色可能重叠混乱。\n",
    "\n",
    "3. **绘制第二个 Stripplot（横向分离）**\n",
    "   - 在同样维度基础上，添加 `dodge=True`；\n",
    "   - 不同颜色（分类）将横向错开显示，更清晰地区分各子类别的分布差异。\n",
    "\n",
    "4. **统一美化**\n",
    "   - 设置 x 轴刻度倾斜 70°，防止部门名称重叠；\n",
    "   - 使用标题说明两个子图的含义；\n",
    "   - 使用 `plt.show()` 展示完整图表。\n",
    "\n",
    "该图表有助于理解 Seaborn 中 `hue + dodge` 参数组合的视觉区别，尤其适合展示分组数据的分布特征。"
   ],
   "id": "335fe9294aa328f2"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T12:15:12.923164Z",
     "start_time": "2025-05-06T12:15:12.289141Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 代码5-36\n",
    "plt.figure(figsize=(10, 13))  # 设置整个图像的大小为10x13英寸\n",
    "\n",
    "plt.subplot(211)  # 创建第一个子图（堆叠显示）\n",
    "plt.xticks(rotation=70)  # 部门名称旋转，防止重叠\n",
    "plt.title('不同部门的平均每月工作时长')  # 设置子图标题\n",
    "sns.stripplot(x='部门', y='每月平均工作小时数（小时）', hue='5年内升职', data=hr2)  # 不同晋升状态在同一位置显示（默认堆叠）\n",
    "\n",
    "plt.subplot(212)  # 创建第二个子图（横向分离显示）\n",
    "plt.xticks(rotation=70)\n",
    "sns.stripplot(x='部门', y='每月平均工作小时数（小时）', hue='5年内升职', data=hr2, dodge=True)  # 设置dodge=True，横向错开显示\n",
    "\n",
    "plt.show()  # 展示完整图像\n"
   ],
   "id": "a08ee0a2b23d0b4b",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Figure size 720x936 with 2 Axes>"
      ],
      "image/png": "[encoded data, 190812 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "execution_count": 40
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 🐝 使用 Swarmplot 显示分组数据的真实分布\n",
    "\n",
    "本程序使用 Seaborn 的 Swarmplot 图展示不同部门中，高薪在职员工的“每月平均工作小时数”分布情况。主要流程如下：\n",
    "\n",
    "1. **绘制 Swarmplot 图**\n",
    "   - Swarmplot 是一种改进的 Stripplot；\n",
    "   - 自动避免数据点重叠，使每个观测点都清晰可见；\n",
    "   - 横轴为“部门”，纵轴为“每月平均工作小时数”。\n",
    "\n",
    "2. **设置图表样式**\n",
    "   - 设置 X 轴刻度标签旋转 70°，防止文字重叠；\n",
    "   - 设置图表标题说明绘图含义。\n",
    "\n",
    "3. **展示图表**\n",
    "   - 使用 `plt.show()` 渲染图像。\n",
    "\n",
    "Swarmplot 图适合用于展示分类变量下的单变量分布，同时保留精度和密度信息。"
   ],
   "id": "ebdf19c0b50a823"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T12:24:17.625175Z",
     "start_time": "2025-05-06T12:24:17.360909Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 代码5-37\n",
    "sns.swarmplot(x='部门', y='每月平均工作小时数（小时）', data=hr2)  # 绘制不同部门的工作时长分布（无重叠散点图）\n",
    "plt.xticks(rotation=70)  # X轴标签旋转，防止重叠\n",
    "plt.title('不同部门的平均每月工作时长')  # 设置图表标题\n",
    "plt.show()  # 显示图表"
   ],
   "id": "bb6f867fe5b8567e",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ],
      "image/png": "[encoded data, 125240 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "execution_count": 41
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 🐝 Swarmplot 分组对比展示晋升与工作时长关系\n",
    "\n",
    "本程序基于高薪在职员工数据，使用 Seaborn 的 `swarmplot()` 展示不同部门员工在“是否在5年内晋升”条件下的“平均每月工作时长”分布。主要流程如下：\n",
    "\n",
    "1. **绘制分组 Swarmplot**\n",
    "   - 横轴为“部门”，纵轴为“每月平均工作小时数”；\n",
    "   - `hue='5年内升职'` 用颜色区分是否晋升；\n",
    "   - Swarmplot 自动排列散点，避免重叠，呈现密度和分布趋势。\n",
    "\n",
    "2. **图表美化**\n",
    "   - 将 X 轴标签旋转 30°，防止部门名称重叠；\n",
    "   - 添加标题说明图表内容。\n",
    "\n",
    "3. **显示图表**\n",
    "   - 使用 `plt.show()` 呈现图形。\n",
    "\n",
    "该图表适合用于对比分类变量组合（部门 × 晋升状态）下的数值分布，直观呈现差异。"
   ],
   "id": "11dfdf781957dad4"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T12:25:01.634493Z",
     "start_time": "2025-05-06T12:25:01.206810Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 代码5-38\n",
    "sns.swarmplot(x='部门', y='每月平均工作小时数（小时）', hue='5年内升职', data=hr2)  # 绘制部门与晋升状态分组的工作时长分布图\n",
    "plt.xticks(rotation=30)  # X轴标签旋转 30 度，避免重叠\n",
    "plt.title('不同部门的平均每月工作时长')  # 设置图表标题\n",
    "plt.show()  # 显示图表"
   ],
   "id": "d460a82c3b53310b",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ],
      "image/png": "[encoded data, 125144 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "execution_count": 42
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 📈 使用 regplot 展示房间数与房价之间的线性关系\n",
    "\n",
    "本程序通过 `sns.regplot()` 展示波士顿房价数据中“房间数”与“房屋价格”之间的线性关系，并对比了默认与自定义置信区间（confidence interval, `ci`）的效果。主要流程如下：\n",
    "\n",
    "1. **创建子图布局**\n",
    "   - 使用 `plt.subplots(1, 2)` 创建一个 1 行 2 列的图像布局；\n",
    "   - 设置整体图像宽高为 8×4 英寸。\n",
    "\n",
    "2. **绘制第一个回归图（默认设置）**\n",
    "   - `sns.regplot()` 默认置信区间为 95%；\n",
    "   - 展示原始散点及拟合直线和误差带。\n",
    "\n",
    "3. **绘制第二个回归图（ci=50）**\n",
    "   - 设置 `ci=50` 表示置信区间改为 50%，误差带更窄；\n",
    "   - 用于强调拟合线更接近中心趋势。\n",
    "\n",
    "4. **添加标题与展示图像**\n",
    "   - 为每个子图添加标题说明；\n",
    "   - 使用 `plt.show()` 显示两个回归图。\n",
    "\n",
    "该图表适合展示变量之间的线性关系以及回归不确定性的可视化表达。"
   ],
   "id": "33f4b514f0f4a345"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T12:25:47.940226Z",
     "start_time": "2025-05-06T12:25:47.581455Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 代码5-39\n",
    "fig, axes = plt.subplots(1, 2, figsize=(8, 4))  # 创建 1 行 2 列的子图布局，图像大小为 8x4 英寸\n",
    "axes[0].set_title('修改前的线性回归拟合图')  # 设置第一个子图的标题\n",
    "axes[1].set_title('修改后的线性回归拟合图')  # 设置第二个子图的标题\n",
    "sns.regplot(x='房间数（间）', y='房屋价格（美元）', data=boston, ax=axes[0])  # 绘制默认置信区间（95%）的线性回归图\n",
    "sns.regplot(x='房间数（间）', y='房屋价格（美元）', data=boston, ci=50, ax=axes[1])  # 绘制置信区间为 50% 的回归图\n",
    "plt.show()  # 显示图像"
   ],
   "id": "5f3df2ac198abaa2",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Figure size 576x288 with 2 Axes>"
      ],
      "image/png": "[encoded data, 60136 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "execution_count": 43
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
