一、实现结果
下面是图片是我实现的一个结果,里面包含两个坐标系。
如果想要实现更多坐标系,请看下面第 第四节 解释。
二、定义画图函数
我将画出的图像的代码部分封装到一个画图函数中,这样将来用到其他的代码中,便于实现。
def draw_function(x1_vals, y1_vals, x2_vals,y2_vals,x_label):
plt.subplot(2,1,1)
plt.xlabel(x_label)
plt.ylabel('Sin')
plt.plot(x1_vals, y1_vals,'-*')
plt.legend(['sin'])
plt.subplot(2,1,2)
plt.xlabel(x_label)
plt.ylabel('Cos')
plt.plot(x2_vals, y2_vals, color='g',linestyle='-.')
plt.legend(['cos'])
plt.show()
三、完整代码
import matplotlib.pyplot as plt
import numpy as np
def draw_function(x1_vals, y1_vals, x2_vals,y2_vals,x_label):
plt.subplot(2,1,1)
plt.xlabel(x_label)
plt.ylabel('Sin')
plt.plot(x1_vals, y1_vals,'-*')
plt.legend(['sin'])
plt.subplot(2,1,2)
plt.xlabel(x_label)
plt.ylabel('Cos')
plt.plot(x2_vals, y2_vals, color='g',linestyle='-.')
plt.legend(['cos'])
plt.show()
x = np.linspace(0, 4* np.pi, 50)
y1 = np.sin(x)
y2 = np.cos(x)
draw_function(x,y1,x,y2,'x',)
四、实现四个坐标系
1.代码解释
plot.subplot(x,y,z)
上面的括号里面字母分表代表 XY代表的坐标轴总共有X行Y列,所以最后总共有 X乘Y个坐标轴,Z代表的是坐标轴为第几个。
2.实现结果
五、进阶版
实现各个坐标图,重点标注单位内Y轴数值异常变化
1. 效果
2. 源码
import matplotlib.pyplot as plt
import numpy as np
def draw_function(x, data):
# 绘制坐标图每个子坐标图对应标签以及单位注明
label_dict = [['sin', 'cos'], ['power', 'exp']]
unit = [['hours', 'min'], ['s', 'ms']]
fig, axes = plt.subplots(len(label_dict), len(label_dict[0]), figsize=(len(label_dict[0])*7, len(label_dict)*3))
for i in range(len(label_dict)):
for j in range(len(label_dict[0])):
label = label_dict[i][j]
y_value = data[label][:]
# 高亮点计算
differences = np.abs(np.diff(y_value))
hight_x = []
hight_y = []
for k in range(len(differences)):
if differences[k] > changeTH:
hight_x.append(x[k + 1])
hight_y.append(y_value[k + 1])
hight_x.append(x[k])
hight_y.append(y_value[k])
axes[i][j].plot(x, y_value, label=label)
axes[i][j].scatter(hight_x, hight_y, color='red', zorder=5)
axes[i][j].set_ylabel(unit[i][j])
axes[i][j].legend([label], loc='lower right')
axes[i][j].set_title(label)
plt.xticks(x)
plt.tick_params(axis='both', labelsize=15)
plt.suptitle('[TITLE: This is a 4*4 subplots.]') # 整个大图标题
plt.tight_layout()
plt.savefig('1.png')
print(f"折线图生成!")
# plt.show()
plt.close()
if __name__ == '__main__':
changeTH = 5
x = np.linspace(0, 4 * np.pi, 50)
data = {
'sin': 10 * np.sin(x),
'cos': 10 * np.cos(x),
'power': np.power(x, 2),
'exp': np.exp(x)
}
draw_function(x, data)