侧边栏壁纸
博主头像
技术探索

行动起来,活在当下

  • 累计撰写 13 篇文章
  • 累计创建 4 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

Python读取csv文件plot画图

admin
2024-12-12 / 0 评论 / 0 点赞 / 11 阅读 / 0 字

生成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)

生成图表:
python-plot.png

0

评论区