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 目录")
最新发布