我有这个代码可以在一个图表中显示来自txt文件的任意数量的数据集。它工作得很好,但我无法弄清楚如何在Matplotlib图形图例中显示所有文件名。我可以获得图中显示的最后一个文件,但这是我能得到的全部内容。那么如何才能让每个文件名都显示在图例中?您可以使用Github https://github.com/thomasawolff/verification_text_data
中的基线文件进行测试def graphWriterIRI():
figsize = plt.figure(figsize=(16,10))
# Set up the plots
plt.subplot(2, 1, 1)
plt.grid(True)
plt.ylabel('IRI value', fontsize=12)
#pylab.ylim([0,150])
plt.title('Right IRI data per mile for verification runs')
plt.tick_params(axis='both', which='major', labelsize=8)
plt.hold(True)
plt.subplot(2, 1, 2)
plt.grid(True)
plt.ylabel('IRI value', fontsize=12)
#pylab.ylim([0,150])
plt.title('Left IRI data per mile for verification runs:')
plt.tick_params(axis='both', which='major', labelsize=8)
plt.hold(True)
# Iterate over the files in the current directory
for filename in os.listdir(os.getcwd()):
# Initialize a new set of lists for each file
startList = []
endList = []
iriRList = []
iriLList = []
# Load the file
if filename.endswith('.TXT'):
with open(filename, 'rU') as file:
for row in csv.DictReader(file):
try:
startList.append(float(row['Start-Mi']))
endList.append(float(row[' End-Mi']))
except:
startList.append(float(row['Start-MP']))
endList.append(float(row[' End-MP']))
try:
iriRList.append(float(row[' IRI R e']))
iriLList.append(float(row['IRI LWP ']))
except:
iriRList.append(float(row[' IRI RWP']))
iriLList.append(float(row['IRI LWP ']))
# Add new data to the plots
try:
plt.subplot(2, 1, 1)
plt.plot(startList,iriRList)
plt.legend([filename]) # shows the last filename in the legend
plt.subplot(2, 1, 2)
plt.plot(startList,iriLList)
plt.legend([filename])
except ValueError:pass
#return iriRList,iriLList
plt.show()
plt.close('all')
graphWriterIRI()
答案 0 :(得分:1)
在循环外生成图例,但请确保实际标记您的图。
def graphWriterIRI():
...
# Iterate over the files in the current directory
for filename in os.listdir(os.getcwd()):
...
if filename.endswith('.TXT'):
with open(filename, 'rU') as file:
for row in csv.DictReader(file):
...
filenames.append(filename)
plt.subplot(2, 1, 1)
plt.plot(startList,iriRList, label=filename)
plt.subplot(2, 1, 2)
plt.plot(startList,iriLList, label=filename)
plt.legend()
plt.show()