python之matplotlib3.(CSV文件操作)

我们可以像如下这样创建一个属于自己的.csv文件,其中的newline=''是为了解决我们创建的CSV文件里多一个空行的问题,用这种方法可以去掉这个空行

import csv
#创建文件对象
f = open('data1.csv','w',encoding='utf-8',newline='')
#基于文件对象构造csv写入对象
csv_write = csv.writer(f)
#构建列表头
csv_write.writerow(['x','y'])
#写入文件内容
csv_write.writerow(['1','3'])
csv_write.writerow(['2','3'])
csv_write.writerow(['3','3'])

#关闭.csv文件
f.close()

使用csv.reader(文件对象)会返回一个和这个文件相关的文件阅读器对象,我们把它保存在reader中,第一次调用next(阅读器)会返回文件的第一行内容,也就是文件的表头。

import csv
filename = 'data1.csv'
with open(filename,'r+') as file_object:
    reader = csv.reader(file_object)
    header_row = next(reader)
    print(header_row)
    header_row = next(reader)
    print(header_row)
    header_row = next(reader)
    print(header_row)

接下来我们打印文件头及其位置,结果如下:0和1是这两个表头的位置,就像数组那样(索引)。

0 x
1 y

import csv
filename = 'data1.csv'
with open(filename,'r+') as file_object:
    reader = csv.reader(file_object)
    header_row = next(reader)
    for index , column_header in enumerate(header_row):
        print(index,column_header)

提取数据,这里会用到for循环来把阅读器读取到的每一行数据保存到列表highs中,知道阅读器把整个文件都月度完成,for循环结束:

import csv
filename = 'data1.csv'
with open(filename,'r+') as file_object:
    reader = csv.reader(file_object)
    header_row = next(reader)
    #提取数据
    highs = []
    for rows in reader:
        highs.append(rows)  #每次提取阅读器返回的一整行
        print(highs)
    # [['1', '3']]
    # [['1', '3'], ['2', '3']]
    # [['1', '3'], ['2', '3'], ['3', '3']]
    highs = []
    for rows in reader:
        highs.append(rows[0]) #每次提取阅读器返回的行的第一列
        print(highs)
    # ['1']
    # ['1', '2']
    # ['1', '2', '3']
    highs = []
    for rows in reader:
        highs.append(rows[1])  # 每次提取阅读器返回的行的第二列
        print(highs)
    # ['3']
    # ['3', '3']
    # ['3', '3', '3']

接下来绘制一个水平线,自己创建.csv文件,程序内写入数据

import csv
from matplotlib import pyplot as plt
from matplotlib.pyplot import MultipleLocator as mulLocal #为了设置xy轴的刻度间隔和范围
#手动创建.csv文件,手动输入数据
#创建文件对象
f = open('data1.csv','w',encoding='utf-8',newline='')
#基于文件对象构造csv写入对象
csv_write = csv.writer(f)
#构建列表头
csv_write.writerow(['x','y'])
#写入文件内容
csv_write.writerow(['0','3'])
csv_write.writerow(['100','3'])
csv_write.writerow(['200','3'])
csv_write.writerow(['300','3'])
#关闭.csv文件
f.close()

filename = 'data1.csv'
#用highx 和 highy 两个列表分别储存data1.csv文件的x和y的数据
with open(filename,'r') as file_object:
    reader = csv.reader(file_object)
    # next()这一步必不可少,是为了往下移动一行,也就是为了避开表头(x,y).否则接下来把数据转化为int类型会报错
    head_row = next(reader)
    highy = []
    highx = []
    for high in reader:
        highx.append(int(high[0]))
        highy.append(int(high[1]))
#plt.figure()中的dpi是设置图像的分辨率默认是100,figsize是来设置图片的宽和高,单位英寸
fig = plt.figure(dpi = 128,figsize=(10,6))
plt.plot(highx,highy,c = 'red')
plt.title('wencha',fontsize = 20)
plt.xlabel('X',fontsize = 12)
plt.ylabel('Y',fontsize = 12)
plt.tick_params(axis='both',labelsize=14)

#把x轴的间隔设置为100,保存在变量x_locator
x_locator = mulLocal(100)
#把y轴的间隔设置为0.5,保存在变量y_locator
y_locator = mulLocal(0.5)
#xy是两条坐标轴的实例
xy = plt.gca()
#把x轴的主刻度设置为100的倍数
xy.xaxis.set_major_locator(x_locator)
#把y轴的主刻度设置为0.5的倍数
xy.yaxis.set_major_locator(y_locator)
#设置x轴的显示范围是0~400
plt.xlim(-0.1,400)
#设置y轴的显示范围是2~4
plt.ylim(2,4)
#inches='tight'  意思是去掉图片的空白部分
plt.savefig('测量常温误差.png',inches='tight')
plt.show()
原文地址:https://www.cnblogs.com/boost/p/13430837.html