导入库
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
设置文字
mpl.rcParams['font.sans-serif'] = ['SimSun'] # 设置中文字体为宋体或其他中文字体名
mpl.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
读取txt文件
# 读取txt文件到array
f = open(r"D:\数据集\data.txt")
line = f.readline()
data_list = []
while line:
num = list(map(float,line.split()))
data_list.append(num)
line = f.readline()
f.close()
data_array = np.array(data_list)
提取数据文件的第7列绘图
# 提取某一列绘图
features = []
targets = []
flag = 1
for item in data_array:
if flag > 1:
features.append([float(item[6])])
targets.append([int(flag)])
flag += 1
数据类型转换
x = np.array(targets)
x = np.squeeze(x)
y = np.array(features)
y = np.squeeze(y)
绘图并保存
plt.plot(x, y, label='数据')
plt.legend()
plt.savefig('p1.jpg',dpi = 600,bbox_inches = "tight")
plt.show()