生成CSV文件
import csv
import math
import numpy as np
def write_csv(filename):
x = [round(i,2) for i in np.arange(0, 7, 0.1)]
y = [round(math.sin(x), 2) for x in x]
data = list(zip(x, y))
with open(filename, 'w') as f:
writer = csv.writer(f)
writer.writerow(['x', 'y']) # 表头
for d in data:
writer.writerow(d)
读取CSV文件
import csv
def read_csv(filename):
x = []
y = []
with open(filename, 'r') as f:
reader = csv.reader(f, delimiter=',')
next(reader) # 跳过表头
for r in reader:
x.append(float(r[0]))
y.append(float(r[1]))
return x,y
CSV文件数据
x,y
0.0,0.0
0.1,0.1
0.2,0.2
0.3,0.3
0.4,0.39
0.5,0.48
...
plot画图
import mplcyberpunk
import matplotlib.pyplot as plt
def plot_csv(x, y):
plt.style.use('cyberpunk') # 美化
plt.plot(x, y, marker='o', label='sin')
plt.legend() # 显示图例
plt.show()
if __name__ == '__main__':
filename = 'test.csv'
write_csv(filename)
x,y = read_csv(filename)
plot_csv(x, y)
生成图表:
评论区