下面是另一个示例,使用numpy、defaultdict、csv.reader()和类:from collections import defaultdict
import csv
import matplotlib.pyplot as plt
import numpy as np
def main():
raw_data = FileReader(fn='salary.csv')
data = ProcessData(raw_data)
Plotter(data)
class ProcessData:
def __init__(self, data):
self.data = data
self.t = sorted(data.years, key=int)
self.names = sorted(list(data.salary.keys()))
self.salary = dict()
self.create_salary_data()
def create_salary_data(self):
for name in self.names:
s = []
for year in self.t:
if year in self.data.salary[name]:
s.append(self.data.salary[name][year])
else:
s.append(None)
self.salary[name] = s
class FileReader:
def __init__(self, **kwargs):
if not 'fn' in kwargs:
raise Exception('No file name given')
self.fn = kwargs['fn']
self.salary = defaultdict(lambda: defaultdict(float))
self.years = set()
self.read_file()
def read_file(self):
with open('salary.csv', newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=';')
header = next(reader)
for row in reader:
if len(row)==0:
continue
if len(row) != 3:
raise Exception('Bad row length in csv file')
name, year, salary = row
self.salary[name][year] = salary
self.years.add(year)
class Plotter:
def __init__(self, data):
self.data = data
t = data.t
names = sorted(list(data.salary.keys()))
fig, ax = plt.subplots()
for name in names:
temp = data.salary[name]
s = list(map(lambda ss: np.nan if ss is None else float(ss), temp))
ax.plot(t, s, label=name)
ax.set(xlabel='Date (year)', ylabel='Salary (\$\$)',
title='Employee salary')
ax.grid()
ax.legend(loc='upper right')
plt.show()
main()