2017-10-28 17 views
0

Irgendwelche Ideen, um den folgenden Code in eine Schleife auf eine gute Weise zu vereinfachen? Der sich wiederholende Code geht an Tausende. z.B. Test-101.csv ... Test-2233.csvVereinfachen Python-Plot mit Legende in Schleife

import pandas as pd 
import matplotlib 
import matplotlib.pyplot as plt 
import numpy as np 


data = pd.read_csv('reports/test-101.csv', header=None) 
line1, = plt.plot(data[2], data[1], label='line 101') 
line1m, = plt.plot(np.array([0, 12]), np.array([np.mean(data[1]), 
np.mean(data[1])]), label='line-101 mean') 

data = pd.read_csv('reports/test-102.csv', header=None) 
line2, = plt.plot(data[2], data[1], label='line 102') 
line2m, = plt.plot(np.array([0, 12]), np.array([np.mean(data[1]), 
np.mean(data[1])]), label='line-102 mean') 

data = pd.read_csv('reports/test-103.csv', header=None) 
line3, = plt.plot(data[2], data[1], label='line 103') 
line3m, = plt.plot(np.array([0, 12]), np.array([np.mean(data[1]), 
np.mean(data[1])]), label='line-103 mean') 
. 
. 
. 


plt.legend(handles=[line1, line2, line3, 
         line1m, line2m, line3m]) 

Antwort

1

Ich glaube, das

import os 

import numpy as np 
import pandas as pd 

from matplotlib import pyplot as plt 

csv_dir = 'reports/' 
csv_files = [csv for csv in os.listdir(csv_dir)] 

plt_handles = [] 
index = 0 

for csv_file in csv_files: 
    # You can parse the csv_file to get the index handle if you wish 
    data = pd.read_csv(csv_dir + csv_file, header=None) 
    line, = plt.plot(data[2], data[1], label='line %d' % index) 
    line_m, = plt.plot(np.array([0, 12]), np.array([np.mean(data[1]), 
     np.mean(data[1])]), label='line-%d mean' % index) 

    plt_handles.append((line, line_m)) 
    index += 1 # for demonstration purposes - if you do not parse csv fname 

lines, lines_m = zip(*plt_handles) # transpose matrix - lines before means 

plt.legend(handles=lines + lines_m) 
+0

Wie helfen könnte genauso gut das Etikett zu Schleife? –

+0

Ich verbesserte die Antwort, vergaß das Label – CermakM

+0

Danke! Gibt es eine Möglichkeit, diese Zeile zu vereinfachen ('line_m, = ...')? –