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

文章讲述了作者在使用seaborn库时遇到的包样式问题,通过网络搜索、更新库版本和检查可用样式列表,最终解决了将seaborn替换为seaborn-v0_8的问题。
'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

C:\python\py\.venv\Scripts\python.exe C:\python\py\图.py Traceback (most recent call last): File "C:\python\py\.venv\Lib\site-packages\matplotlib\style\core.py", line 129, in use style = _rc_params_in_file(style) File "C:\python\py\.venv\Lib\site-packages\matplotlib\__init__.py", line 903, in _rc_params_in_file with _open_file_or_url(fname) as fd: ~~~~~~~~~~~~~~~~~^^^^^^^ File "C:\Users\Ran\AppData\Local\Programs\Python\Python313\Lib\contextlib.py", line 141, in __enter__ return next(self.gen) File "C:\python\py\.venv\Lib\site-packages\matplotlib\__init__.py", line 880, in _open_file_or_url with open(fname, encoding='utf-8') as f: ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^ FileNotFoundError: [Errno 2] No such file or directory: 'seaborn-whitegrid' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\python\py\图.py", line 10, in <module> plt.style.use('seaborn-whitegrid') ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^ File "C:\python\py\.venv\Lib\site-packages\matplotlib\style\core.py", line 131, in use raise OSError( ...<2 lines>... f"styles are listed in `style.available`)") from err OSError: 'seaborn-whitegrid' 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`) 进程已结束,退出代码为 1 修改下面代码 import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from scipy.signal import savgol_filter from matplotlib.gridspec import GridSpec import os # 设置全局样式 plt.style.use('seaborn-whitegrid') plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'DejaVu Sans'] plt.rcParams['axes.unicode_minus'] = False plt.rcParams['figure.dpi'] = 100 plt.rcParams['savefig.dpi'] = 300 plt.rcParams['font.size'] = 10 sns.set_palette('Set2') def read_data(file_path): """读取数据文件""" if file_path.endswith('.xlsx'): df = pd.read_excel(file_path) else: encodings = ['utf-8', 'gbk', 'latin1'] for encoding in encodings: try: df = pd.read_csv(file_path, encoding=encoding) break except: continue return df.sort_values('wavenumber').reset_index(drop=True) def generate_plots(df, title, file_name, zoom_regions): """生成主图和放大子图""" fig = plt.figure(figsize=(15, 10), tight_layout=True) fig.suptitle(title, fontsize=16, y=0.98) # 创建网格布局 gs = GridSpec(2, len(zoom_regions) + 1, height_ratios=[2, 1], width_ratios=[1.5] + [1] * len(zoom_regions)) # 主图 ax_main = fig.add_subplot(gs[0, 0]) ax_main.plot(df['wavenumber'], df['reflectance'], color='#1f77b4', label='原始数据', alpha=0.7) if 'reflectance_smooth' in df.columns: ax_main.plot(df['wavenumber'], df['reflectance_smooth'], color='#ff7f0e', label='平滑数据', linewidth=2) ax_main.set_title('完整光谱') ax_main.set_xlabel('波数 ($cm^{-1}$)') ax_main.set_ylabel('反射率 (%)') ax_main.legend(loc='best') ax_main.grid(True, linestyle=':', alpha=0.6) # 标记放大区域 colors = ['#d62728', '#2ca02c', '#9467bd'][:len(zoom_regions)] for i, (start, end) in enumerate(zoom_regions): ymin, ymax = ax_main.get_ylim() rect = plt.Rectangle((start, ymin), end - start, ymax - ymin, fill=False, edgecolor=colors[i], linestyle='--', linewidth=1.5, alpha=0.8) ax_main.add_patch(rect) # 放大区域子图 for i, (start, end) in enumerate(zoom_regions): ax_zoom = fig.add_subplot(gs[1, i + 1]) zoom_df = df[(df['wavenumber'] >= start) & (df['wavenumber'] <= end)] ax_zoom.plot(zoom_df['wavenumber'], zoom_df['reflectance'], color='#1f77b4', label='原始数据', alpha=0.7) if 'reflectance_smooth' in df.columns: ax_zoom.plot(zoom_df['wavenumber'], zoom_df['reflectance_smooth'], color='#ff7f0e', label='平滑数据', linewidth=2) ax_zoom.set_title(f'{start}-{end} $cm^{-1}$ 区间') ax_zoom.set_xlabel('波数 ($cm^{-1}$)') ax_zoom.set_ylabel('反射率 (%)') diff = zoom_df['reflectance'].max() - zoom_df['reflectance'].min() ax_zoom.set_ylim(zoom_df['reflectance'].min() - diff * 0.1, zoom_df['reflectance'].max() + diff * 0.1) ax_zoom.grid(True, linestyle=':', alpha=0.6) if i == 0: ax_zoom.legend(loc='best') # 保存图像 plt.savefig(f'results/{file_name}_plots.png', bbox_inches='tight') plt.close() # 主程序 if __name__ == '__main__': # 创建输出目录 if not os.path.exists('results'): os.makedirs('results') # 附件1处理 file1 = r'C:\Users\Ran\Desktop\附件1.xlsx' df1 = read_data(file1) df1['reflectance_smooth'] = savgol_filter(df1['reflectance'], window_length=51, polyorder=3) generate_plots(df1, '附件1: 原始数据与平滑数据对比', 'attachment1', [(1500, 1700)]) # 附件2处理 file2 = r'C:\Users\Ran\Desktop\附件2.xlsx' df2 = read_data(file2) df2['reflectance_smooth'] = savgol_filter(df2['reflectance'], window_length=51, polyorder=3) generate_plots(df2, '附件2: 原始数据与平滑数据对比', 'attachment2', [(1500, 1700), (3000, 3400)]) print("四个图表已生成并保存到 results 目录")
最新发布
09-06
为什么运行结果显示: Traceback (most recent call last): File "C:\Users\漠漠\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\matplotlib\style\core.py", line 129, in use style = _rc_params_in_file(style) File "C:\Users\漠漠\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\matplotlib\__init__.py", line 903, in _rc_params_in_file with _open_file_or_url(fname) as fd: File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\Lib\contextlib.py", line 137, in __enter__ return next(self.gen) File "C:\Users\漠漠\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\matplotlib\__init__.py", line 880, in _open_file_or_url with open(fname, encoding='utf-8') as f: FileNotFoundError: [Errno 2] No such file or directory: 'seaborn' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:/日常文件夹/python7.py", line 21, in <module> plt.style.use('seaborn') File "C:\Users\漠漠\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\matplotlib\style\core.py", line 131, in use raise OSError( OSError: '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`) 解决代码中的问题,不要改变代码的功能,给出优化修改后完整的代码,
06-10
评论 8
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值