You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Matplotlib的plt.savefig时触发ENOSPC错误的原因咨询

问题:Matplotlib保存图片时触发ENOSPC(设备无剩余空间)错误

问题现象

  • 执行plt.savefig(f'outputs/{filename}_xyz.png', dpi=400)代码行时,触发ENOSPC(No space left on device,设备无剩余空间)错误
  • 注释掉该行后,脚本可正常运行并显示图片
  • 同时出现Jupyter Notebook保存错误:

File Save Error for Untitled.ipynb
Unexpected error while saving file: Untitled.ipynb [Errno 28] No space left on device

相关代码

import pandas as pd
quantaq_file = 'MOD8765.csv'
quantaq = pd.read_csv(quantaq_file)
quantaq.head(2)

quantaq['timestamp_local'] = pd.to_datetime(quantaq['timestamp_local'])

desired_format = '%Y-%m-%d %H:%M'

quantaq['timestamp_local'] = quantaq['timestamp_local'].dt.strftime(desired_format)

print(quantaq.head(2))
quantaq = quantaq.rename(columns={'timestamp_local':"Time",'pm25':"pm25_quantaq"})
quantaq['Time'] = pd.to_datetime(quantaq['Time'])
quantaq = quantaq[["Time","pm25_quantaq"]]
quantaq.set_index("Time", inplace=True)
quantaq = quantaq.resample("h").mean()
#quantaq = quantaq[quantaq.index >'2024-04-01 00:00:00']
quantaq

import os
import pandas as pd

folder_path = 'TARA_UNDP' 

for file in os.listdir(folder_path):
    if file.endswith('xlsx'):
        file_path = os.path.join(folder_path, file)
        print(f"Processing file: {file_path}")

        filename = os.path.basename(file_path).split(".")[0]
        print(f"Filename: {filename}")

        excel_data = pd.read_excel(file_path, sheet_name=None, header=None)
        
        for sheet_name, sheet_df in excel_data.items():
            print(f"Processing sheet: {sheet_name}")
            try:
                df = sheet_df.copy()
                df = df.iloc[:, :4] 
                df.columns = ['Date', 'ID', 'pm25_undp', 'pm10_undp']
                df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%Y_%H:%M', errors='coerce')
    
                df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%Y_%H:%M')
                df['Date'] = df['Date'].dt.strftime('%Y-%m-%d %H:%M:%S')
    
                print(df.head(), len(df))
    
                df['Date'] = pd.to_datetime(df['Date'])
                df = df[["Date", "pm25_undp"]]
                df.set_index("Date", inplace=True)
    
                df = df.resample("h").mean()
                print("Resampled DataFrame:")
                print(df)
    
                merge = pd.merge(quantaq, df, left_index=True, right_index=True, how='inner')
                merge = merge.dropna()
           
                print("Merged DataFrame:")
                print(merge)
                import pandas as pd
                import matplotlib.pyplot as plt
                import matplotlib.dates as mdates
                
                
                
                df1 = merge
                
                plt.figure(figsize=(10, 6))
                
                plt.plot(df1.index, df1['pm25_undp'], label='PM2.5_UNDP')
                plt.plot(df1.index, df1['pm25_quantaq'], label='pm25_quantaq')
                
                plt.title(f'PM2.5 Measurements Over Time: {filename}:{sheet_name}')
                plt.xlabel('Time')
                plt.ylabel('PM2.5 Values (µg/m³)')
                plt.legend()
                plt.xticks(rotation=45)  
                
                r_values = {
                    # 'PM2.5_UNDP': df1['pm25_undp'].corr(df1['pm25_quantaq']),
                    'pm25_quantaq': df1['pm25_quantaq'].corr(df1['pm25_undp'])
                }
                textstr = f'{sheet_name}:PM2.5_UNDP Correlation with:-\n' + '\n'.join([f'- {sensor}: {r_value:.4f}' for sensor, r_value in r_values.items()])
                props = dict(boxstyle='round', facecolor='white', alpha=0.9)
                
                plt.text(0.23, 0.97, textstr, transform=plt.gca().transAxes, fontsize=10, verticalalignment='top', bbox=props)
                
                plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M'))
                plt.gca().xaxis.set_major_locator(mdates.HourLocator(interval=1))  
                
                plt.xticks(rotation=45)
                
                plt.tight_layout()
                plt.grid(True)
                
                plt.savefig(f'outputs/{filename}_{sheet_name}_undp_iitd.png', dpi=400)
                plt.show()
            except Exception as e:
                print(f"Error processing sheet {filename}:{sheet_name}: {e}")
                continue  

错误原因

ENOSPC错误的核心就是你的设备存储分区已经没有剩余空间了,对应你的场景:

  1. plt.savefig需要将生成的图片写入outputs目录所在的磁盘分区,当分区空间耗尽时,写入操作直接失败,触发该错误。
  2. Jupyter Notebook保存Untitled.ipynb也失败,进一步证明了存储分区空间不足——Notebook的保存路径和图片输出路径大概率在同一个分区。
  3. 注释掉plt.savefig后脚本能正常运行,是因为显示图片只占用内存,不需要写入磁盘,所以不会触发磁盘空间不足的错误。

内容的提问来源于stack exchange,提问作者Eren_anad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 11:57:35