使用matplotlib绘图的简单方法
1、如何从.csv中读取数据呢
举例,从某表格读取数据。例如:
train-tag-Loss_Batch_coarse1.csv
train-tag-Loss_Batch_coarse2.csv
代码如下:
import csv
csvFile_1 = open("train-tag-Loss_Batch_coarse1.csv", "r")
csvFile_2 = open("train-tag-Loss_Batch_coarse2.csv", "r")
reader_1 = csv.reader(csvFile_1)
reader_2 = csv.reader(csvFile_2)
# build a dict
x_1 = []
y_1 = []
x_2 = []
y_2 = []
for item in reader_1:
# ignore the first line
if reader_1.line_num == 1:
continue
x_1.append(float(item[1]))
y_1.append(float(item[2]))
for item in reader_2:
# ignore the first line
if reader_2.line_num == 1:
continue
x_2.append(float(item[1]))
y_2.append(float(item[2]))
csvFile_1.close()
csvFile_2.close()
2、对数据进行处理,为了使其更加平滑
这里是将数据进行一些数量级的变化,同时为了更好的做出曲线,将x的范围规定为某一范围的均匀间隔点。同时使用 nearest 规则进行曲线回归,生成较为平滑的曲线。
x_1 = np.array(x_1)
y_1 = np.array(y_1) * 0.1
x_2 = np.array(x_2)
y_2 = np.array(y_2) * 0.1
xnew = np.linspace(x_1.min(), x_1.max(), 1000, endpoint=False)
# 1000 represents number of points to make between T.min and T.max
f_1 = interp1d(x_1, y_1, kind="nearest")
f_2 = interp1d(x_2, y_2, kind="nearest")
3、数据准备完毕之后,规定绘图的一些规则
这个使用的 plt 的 style 是 fivethirtyeight ,可以根据官网的介绍选择自己喜欢的。scaling 是自己为了调整图的大小设定的。之后分别设定 legend, axes, xtick, ytick 的大小,规定绘图的 figsize 。其余的参数可以根据自己的喜好进行设定
plt.style.use("fivethirtyeight")
scaling = 3
params = {
"font.size": 14 * scaling,
"legend.fontsize": 14 * scaling,
"axes.labelsize": 14 * scaling,
"xtick.labelsize": 14 * scaling,
"ytick.labelsize": 14 * scaling,
"text.usetex": True,
"figure.figsize": [20, 20 / 1.618],
"font.family": "serif",
"font.sans-serif": "Times",
"axes.facecolor": "white",
}
rcParams.update(params)
4、终于,一切准备妥当,可以进行绘图
规定一些参数,后面会使用
LINEWIDTH = 3.0 * scaling
MARKERSIZE = 10 * scaling
WIDTH = 3.36 * 5
HEIGHT = 3.36 / 1.618 * 5
之后,设定图像的背景颜色,使用 subplot 进行绘图范围的划定,这个使用逻辑和 matlab 保持一致。之后使用 subplots_adjust 函数进行图像的留边。
fig = plt.figure()
fig.patch.set_facecolor("white")
plt.subplot(1, 1, 1)
fig.subplots_adjust(left=0.10, bottom=0.2, right=0.95, top=0.95)
开始绘制图像
alpha 是用于设定曲线的透明度。
plt.plot(xnew, f_1(xnew), label="1", linewidth=LINEWIDTH, markersize=MARKERSIZE, alpha=0.7)
plt.plot(xnew, f_2(xnew), label="2", linewidth=LINEWIDTH, markersize=MARKERSIZE, alpha=0.7)
plt.legend(loc="upper right", frameon=False)
绘制图像的坐标
plt.xticks((2048, 4096, 8192, 16384), [r"$2048$", r"$4096$", r"$8192$", r"$16384$"])
plt.yticks()
plt.xlabel("x")
plt.ylabel(r"y")
限定图像的坐标范围
plt.ylim(1, 7) # 限定纵轴的范围
最后调整图像的大小范围,展示结果
fig.set_size_inches(WIDTH, HEIGHT)
plt.show()
5、绘制图像完毕,开始存储图像
可以保存为pdf格式文件
foo_fig.savefig("coarse.pdf", format="pdf", dpi=600, transparent=True)
foo_fig = plt.gcf()
6、结果展示
7、完整代码
import csv
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
import pandas as pd
import matplotlib as mlp
from matplotlib import rcParams
# read from csv
csvFile_1 = open("1_train-tag-Loss_Batch_coarse.csv", "r")
csvFile_2 = open("2_train-tag-Loss_Batch_coarse.csv", "r")
reader_1 = csv.reader(csvFile_1)
reader_2 = csv.reader(csvFile_2)
# build a dict
x_1 = []
y_1 = []
x_2 = []
y_2 = []
for item in reader_1:
# ignore the first line
if reader_1.line_num == 1:
continue
x_1.append(float(item[1]))
y_1.append(float(item[2]))
for item in reader_2:
# ignore the first line
if reader_2.line_num == 1:
continue
x_2.append(float(item[1]))
y_2.append(float(item[2]))
csvFile_1.close()
csvFile_2.close()
x_1 = np.array(x_1)
y_1 = np.array(y_1) * 0.1
x_2 = np.array(x_2)
y_2 = np.array(y_2) * 0.1
xnew = np.linspace(x_1.min(), x_1.max(), 30, endpoint=False) # 1000 represents number of points to make between T.min and T.max
f_1 = interp1d(x_1, y_1, kind="nearest")
f_2 = interp1d(x_2, y_2, kind="nearest")
plt.style.use("fivethirtyeight")
scaling = 3
params = {
"font.size": 14 * scaling,
"legend.fontsize": 14 * scaling,
"axes.labelsize": 14 * scaling,
"xtick.labelsize": 14 * scaling,
"ytick.labelsize": 14 * scaling,
"text.usetex": True,
"figure.figsize": [20, 20 / 1.618],
"font.family": "serif",
"font.sans-serif": "Times",
"axes.facecolor": "white",
}
rcParams.update(params)
LINEWIDTH = 3.0 * scaling
MARKERSIZE = 10 * scaling
WIDTH = 3.36 * 5
HEIGHT = 3.36 / 1.618 * 5
fig = plt.figure()
fig.patch.set_facecolor("white")
plt.subplot(1, 1, 1)
fig.subplots_adjust(left=0.10, bottom=0.2, right=0.95, top=0.95)
plt.plot(xnew, f_1(xnew), label="example1", linewidth=LINEWIDTH, markersize=MARKERSIZE, alpha=0.7)
plt.plot(xnew, f_2(xnew), label="example2", linewidth=LINEWIDTH, markersize=MARKERSIZE, alpha=0.7)
# plt.xticks((2048, 4096, 8192, 16384), [r"$2048$", r"$4096$", r"$8192$", r"$16384$"])
plt.xticks()
plt.yticks()
plt.ylim(1, 7) # 限定纵轴的范围
plt.xlabel("x")
plt.ylabel(r"y")
plt.legend(loc="upper right", frameon=False)
fig.set_size_inches(WIDTH, HEIGHT)
foo_fig = plt.gcf()
plt.show()
foo_fig.savefig("coarse.pdf", format="pdf", dpi=600, transparent=True)