plt.style.use(‘seaborn‘)出错

'seaborn' is not a valid package style, path of style file, URL of style file, or library style name (library styles are listed in `style.available`)

调用Matplotlib内置样式时报错:

首先尝试网络常见的解决办法

检查安装seaborn:

pip install seaborn

然后在代码当中调用:

import seaborn

发现依旧报错

换一个样式:

plt.style.use('seaborn-darkgrid')

还是报错!

搜索无果,老办法:查询源头的可用样式列表

plt.style.available

结果发现

应该是更新了吧,没有“seaborn”只有“seaborn-v0_8”,修改代码

plt.style.use('seaborn-v0_8')

调用成功!!!

t

import pandas as pd import numpy as np import os import matplotlib.pyplot as plt from tqdm import tqdm from concurrent.futures import ProcessPoolExecutor # ========== 配置参数 ========== D_TYPE = {0: np.float32, 1: np.float32} CHUNK_SIZE = 10000 # ========== 数据处理函数 ========== def process_sheet(df: pd.DataFrame, target: float) -> float: """处理单个工作表的核心逻辑""" valid_mask = df.iloc[:, [0,1]].notna().all(axis=1) a_col = df.iloc[valid_mask, 0].astype(np.float32) b_col = df.iloc[valid_mask, 1].astype(np.float32) mask = a_col.between( target - 0.003, target + 0.003, inclusive='both' ) return b_col[mask].sum() def process_excel(file_path: str, target: float) -> float: """处理单个Excel文件的并行单元""" try: all_sheets = pd.read_excel( file_path, sheet_name=None, skiprows=5, usecols="A:B", header=None, dtype=D_TYPE, engine='openpyxl' ) total = sum( process_sheet(df, target) for df in all_sheets.values() ) return total / len(all_sheets) except Exception as e: print(f"处理文件 {os.path.basename(file_path)} 时出错: {str(e)}") return 0.0 # ========== 主处理流程 ========== if __name__ == "__main__": # 初始化中文字体配置(核心修复) plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'KaiTi'] # 多字体备选 plt.rcParams['axes.unicode_minus'] = False # 用户输入 target_value = float(input("请输入要筛选的A列目标值:")) input_dir = input("请输入Excel文件所在的文件夹路径:").strip() output_dir = input("请输入结果图表输出路径:").strip() os.makedirs(output_dir, exist_ok=True) # 获取文件列表 files = [ os.path.join(input_dir, f) for f in os.listdir(input_dir) if f.endswith(".xlsx") ] # 并行处理 with ProcessPoolExecutor() as executor: futures = { executor.submit(process_excel, file, target_value): os.path.basename(file) for file in files } results = [] with tqdm(total=len(files), desc="处理进度") as pbar: for future in futures: filename = futures[future] try: avg_sum = future.result() results.append((filename, avg_sum)) except Exception as e: print(f"文件 {filename} 处理异常: {str(e)}") finally: pbar.update(1) # ========== 可视化优化 ========== plt.style.use('seaborn-v0_8-darkgrid') plt.figure(figsize=(12, 6), dpi=100) plt.barh( [x[0] for x in results], [x[1] for x in results], color='#4C72B0' ) plt.xlabel("B列总和平均值", fontsize=12, fontweight='bold') plt.ylabel("文件名", fontsize=12, fontweight='bold') plt.title(f"目标值 {target_value}±0.003 数据统计\n({len(files)}个文件)", fontsize=14, pad=20) plt.grid(axis='x', linestyle='--', alpha=0.7) # 调整布局和保存 plt.tight_layout() output_path = os.path.join(output_dir, "optimized_result.png") plt.savefig(output_path, dpi=300, bbox_inches='tight') print(f"\n处理完成!优化结果图表已保存至:{output_path}") 这段代码的文字路径在哪修改
03-19
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值