【附代码】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]
相关推荐
技术猴小猴3 小时前
如何使用Python实现LRU缓存
python·spring·缓存
2401_841495643 小时前
【自然语言处理】“bert-base-chinese”的基本用法及实战案例
人工智能·python·自然语言处理·bert·文本预处理·特征提取·训练验证
猫头虎3 小时前
AI_NovelGenerator:自动化长篇小说AI生成工具
运维·人工智能·python·自动化·aigc·gpu算力·ai-native
l1t3 小时前
DeepSeek辅助测试三种ODS电子表格写入程序
python·xlsx·ods·deepseek·xlsb
Full Stack Developme4 小时前
Python Calendar 模块教程
java·服务器·python
2401_831501735 小时前
Python学习之Day07-08学习(Django网页Web开发)
python·学习·django
Tiny番茄5 小时前
leetcode 3. 无重复字符的最长子串
数据结构·python·算法·leetcode
胡斌附体6 小时前
离线docker安装jupyter(python网页版编辑器)
python·docker·jupyter·image·tar·save
java1234_小锋7 小时前
TensorFlow2 Python深度学习 - TensorFlow2框架入门 - 使用Keras实现逻辑回归
python·深度学习·tensorflow·tensorflow2