Skip to main content
 首页 » 编程设计

python之在循环中绘制图形

2025年05月04日14cmt

我在一个文件夹中有 2 个 csv 文件,如下所示:

(文件 1)

Count      Bins 
0       -0.322392 
1       -0.319392 
1       -0.316392 
0       -0.313392 
2       -0.310392 
1       -0.307392 
5       -0.304392 
4       -0.301392 

(文件 2)

Count      Bins 
5       -0.322392 
1       -0.319392 
1       -0.316392 
6       -0.313392 
2       -0.310392 
1       -0.307392 
2       -0.304392 
4       -0.301392 

我想用 x 轴上的 Bins 与 y 轴上的 Count 制作一个折线图。所以每张图中只有一条线。到目前为止我正在使用这段代码:

import pandas as pd 
import os 
import matplotlib.pyplot as plt 
from matplotlib.backends.backend_pdf import PdfPages 
 
#path where csv files are stored 
pth = (r'F:\Sheyenne\Statistics\IDL_stats\NDII-2') 
 
#initiate loop 
for f in os.listdir(pth): 
    if not os.path.isfile(os.path.join(pth,f)): 
        continue 
    #read each file 
    df = pd.read_csv(os.path.join(pth, f)) 
    #add column names 
    df.columns=['Count', 'Bins'] 
    #create pdf file to save graphs to 
    with PdfPages(r'F:\Sheyenne\Statistics\IDL_stats\Delete.pdf') as pdf: 
         #plot the graph 
         df2=df.plot(title=str(f)) 
         #set x-label 
         df2.set_xlabel("Bins") 
         #set y-label 
         df2.set_ylabel("Count") 
         #save the figure 
         pdf.savefig(df2) 
         #close the figure 
         plt.close(df2) 
print "Done Processing"   

但这绘制了两条线,一条用于Count,另一条用于Bins。它还只绘制第一个文件而不是返回错误的第二个文件:

Traceback (most recent call last): 
 
  File "<ipython-input-5-b86bf00675fa>", line 1, in <module> 
    runfile('F:/python codes/IDL_histograms.py', wdir='F:/python codes') 
 
  File "C:\Users\spotter\AppData\Local\Continuum\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 685, in runfile 
    execfile(filename, namespace) 
 
  File "C:\Users\spotter\AppData\Local\Continuum\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 71, in execfile 
    exec(compile(scripttext, filename, 'exec'), glob, loc) 
 
  File "F:/python codes/IDL_histograms.py", line 26, in <module> 
    pdf.savefig(df2) 
 
  File "C:\Users\spotter\AppData\Local\Continuum\Anaconda\lib\site-packages\matplotlib\backends\backend_pdf.py", line 2438, in savefig 
    raise ValueError("No such figure: " + repr(figure)) 
 
ValueError: No such figure: <matplotlib.axes._subplots.AxesSubplot object at 0x0D628FB0> 

请您参考如下方法:

Pandas DataFrame.plot() 返回 matplotlib axis object , 但 savefig 需要一个 fig 对象。使用 plt.gcf() 获取当前的 matplotlib 图并保存。

# Open the pdf before looping to add pages 
with PdfPages(r'C:\test\Delete.pdf') as pdf: 
    for f in os.listdir(pth): 
        if not os.path.isfile(os.path.join(pth,f)): 
            continue 
        # ignore the pdf file that just got created 
        if 'pdf' in f: 
            continue 
        #read each file 
        df = pd.read_csv(os.path.join(pth, f)) 
        #add column names 
        df.columns=['Count', 'Bins'] 
        #create pdf file to save graphs to 
        #plot the graph 
        df2=df.plot(title=str(f)) 
        #set x-label 
        df2.set_xlabel("Bins") 
        #set y-label 
        df2.set_ylabel("Count") 
        #save the figure 
        fig = plt.gcf() 
        pdf.savefig(fig) 
        #close the figure 
        plt.close(fig) 

适合我。