【附代码】Jupyter 多进程调用 seaborn 并保留格式

文章目录

Jupyter 多进程调用 seaborn 格式会和单进程使用不统一,本文将解决以上问题。

Jupyter 多进程的简单例子

Jupyter 中直接使用多进程可能会有诸多问题,推荐把 function 放在 .py文件里,然后在 Jupyter 中多进程调用。

文件目录

bash 复制代码
PythonProject
├─csdn_jupyter_multiprocessing
│    example_multiprocessing.ipynb
│    function.py

代码

python 复制代码
# example_multiprocessing.ipynb

from concurrent.futures import ProcessPoolExecutor
from tqdm import tqdm
from csdn_jupyter_multiprocessing.function import square

if __name__ == '__main__':
    with ProcessPoolExecutor(max_workers=2) as executor:
        results = list(tqdm(
            executor.map(square, [1, 2, 3, 4, 5]),
            total=5,
            desc="计算中",
            unit="任务"
        ))
    print(results)
python 复制代码
# function.py

def square(x):
    return x * x

运行结果

bash 复制代码
计算中: 100%|██████████| 5/5 [00:00<00:00, 92.59任务/s]
[1, 4, 9, 16, 25]

Jupyter 多进程调用 seaborn(保留格式)

核心思路是主进程中把 sns.axes_style() 传递到子进程。

文件目录

bash 复制代码
PythonProject
├─csdn_jupyter_multiprocessing
│    example_multiprocessing.ipynb
│    function.py

代码

python 复制代码
# example_multiprocessing.ipynb

from concurrent.futures import ProcessPoolExecutor
from tqdm import tqdm
from csdn_jupyter_multiprocessing.function import seaborn_example
import seaborn as sns

if __name__ == '__main__':
    seaborn_style = sns.axes_style()
    with ProcessPoolExecutor(max_workers=2) as executor:
        list(tqdm(
            executor.map(seaborn_example, [('0.svg', seaborn_style), ('1.svg', seaborn_style)]),
            total=2,
            desc="计算中",
            unit="任务"
        ))
python 复制代码
# function.py

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

def seaborn_example(args):
    save_name, seaborn_style = args
    sns.set_style(seaborn_style)

    # 创建示例数据:模拟某产品每日销售额
    days = np.arange(1, 31)  # 1到30天
    sales = np.random.normal(loc=100, scale=15, size=30).cumsum() + 1000  # 模拟销售额趋势

    # 构建DataFrame
    data = pd.DataFrame({
        'Day': days,
        'Sales': sales
    })

    # 绘制基础线图
    sns.lineplot(data=data, x='Day', y='Sales')
    plt.savefig(save_name)
    plt.close()

运行结果

bash 复制代码
计算中: 100%|██████████| 2/2 [00:01<00:00,  1.66任务/s]
相关推荐
m0_613607011 天前
小土堆-P3-笔记
pytorch·python·深度学习
rgeshfgreh1 天前
Python高效开发:标准库与第三方库实战指南
python
虎冯河1 天前
阿里云 + 宝塔面板环境Python 项目从 0 到 1 部署全流
python·阿里云·云计算
鹿衔`1 天前
PySpark 大规模造数任务优化与实施总结文档
python·pyspark
深蓝海拓1 天前
PySide6从0开始学习的笔记(二十三)使用QRunnable在线程池中执行临时任务
笔记·python·qt·学习·pyqt
CCPC不拿奖不改名1 天前
网络与API:HTTP基础+面试习题
网络·python·网络协议·学习·http·面试·职场和发展
MistaCloud1 天前
Pytorch深入浅出(十五)之GPU加速与设备管理
人工智能·pytorch·python·深度学习
Aurora-Borealis.1 天前
Day31 函数专题2
python
蓝冰凌1 天前
python版本管理工具
python
Data_agent1 天前
Pantherbuy模式淘宝 / 1688 代购系统(欧美市场)搭建指南
大数据·python·产品经理