1.在坐标轴中添加x轴和Y轴标签
Axes.set_xlabel(xlabel, fontdict=None, labelpad=None, *, loc=None, **kwargs)
示例
1 导入模块
import matplotlib.pyplot as plt
import numpy as np
2 创建画布,添加数据,绘制图表
fig = plt.figure()
ax = fig.add_subplot(111)
# 准备数据
x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
y1,y2 = np.sin(x),np.cos(x)
# 绘制图表
ax.plot(x,y1,x,y2)
3 添加标签,x,y轴命名,展示图表
ax.set_xlabel('x轴') # x轴
ax.set_ylabel('y轴') # y轴
plt.show()
2.在图表添加标题
语法如下:
matplotlib.pyplot.title(label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs)
示例:
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
fig = plt.figure()
ax = fig.add_subplot(111)
x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
y1, y2 = np.sin(x), np.cos(x)
ax.plot(x,y1,x,y2)
ax.set_xlim(x.min() * 1.5, x.max() * 1.5) # 刻度范围
ax.set_xticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi]) # 刻度位置
ax.set_xticklabels([r'$-\pi$', r'$-\pi/2$', r'$0$', r'$\pi/2$', r'$\pi$']) # 刻度标签
ax.set_xlabel('x轴')
ax.set_ylabel('y轴')
ax.set_title('正余弦曲线展示')
plt.show()
3 在图表中添加图例
语法如下:
Axes.legend(*args, **kwargs)
示例:
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
fig = plt.figure()
ax = fig.add_subplot(111)
x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
y1, y2 = np.sin(x), np.cos(x)
legend_labels = ['正弦曲线','余弦曲线']
lines = ax.plot(x, y1, x, y2)
ax.set_xlabel('x轴')
ax.set_ylabel('x轴')
ax.set_xlim(x.min() * 1.5, x.max() * 1.5) # 刻度范围
ax.set_xticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi]) # 刻度位置
ax.set_xticklabels([r'$-\pi$', r'$-\pi/2$', r'$0$', r'$\pi/2$', r'$\pi$']) # 刻度标签
ax.set_title('正余弦曲线展示')
ax.legend(lines,legend_labels,shadow=True,fancybox=True)
plt.show()
4 图表中辅助线的绘制
语法:
Axes.grid(visible=None, which='major', axis='both', **kwargs)
示例:
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
fig = plt.figure()
ax = fig.add_subplot(111)
x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
y1, y2 = np.sin(x), np.cos(x)
legend_labels = ['正弦曲线','余弦曲线']
lines = plt.plot(x, y1, x, y2)
ax.set_xlabel('x轴')
ax.set_ylabel('x轴')
ax.set_xlim(x.min() * 1.5, x.max() * 1.5) # 刻度范围
ax.set_xticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi]) # 刻度位置
ax.set_xticklabels([r'$-\pi$', r'$-\pi/2$', r'$0$', r'$\pi/2$', r'$\pi$']) # 刻度标签
ax.set_title('正余弦曲线展示')
ax.legend(lines,legend_labels,shadow=True,fancybox=True)
ax.grid(axis='y',lw=0.3)
plt.show()