备赛笔记:matplotlib学习笔记
1 创建figure对象才能开始绘图
import matplotlib.pyplot as plt fig = plt.figure()
2 创建轴作为画图基准
ax = fig.add_subplot(111)
ax.set(xlim=[0.5, 4.5], ylim=[-2, 8], title=An Example Axes,
ylabel=Y-Axis, xlabel=X-Axis)
plt.show()
fig.add_subplot()指将画布几等分。111为整个画布
ax.set函数里xlim为x坐标上下限,ylim为y坐标上下限,title为图表名称,ylabel,xlable为y轴和x轴的名称
fig = plt.figure() ax1 = fig.add_subplot(221) ax2 = fig.add_subplot(222) ax3 = fig.add_subplot(223) ax4 = fig.add_subplot(224)
把画布二等分一共可以画4个图,第三个参数对应画布位置
一次创建多个轴并保存至一个二维数组
fig, axes = plt.subplots(nrows=2, ncols=2) axes[0,0].set(title=Upper Left) axes[0,1].set(title=Upper Right) axes[1,0].set(title=Lower Left) axes[1,1].set(title=Lower Right)
使用plot函数画线,前两个参数对应x,y轴数据,后面可以添加颜色,线型等参数
x = np.linspace(0, np.pi) y_sin = np.sin(x) y_cos = np.cos(x) ax1.plot(x, y_sin) ax2.plot(x, y_sin, go--, linewidth=2, markersize=12) ax3.plot(x, y_cos, color=red, marker=+, linestyle=dashed)
fig.clear()
清除画布,清除所有轴和图象
传入字典的字符串键画图:
x = np.linspace(0, 10, 200)
data_obj = {
x: x,
y1: 2 * x + 1,
y2: 3 * x + 1.2,
mean: 0.5 * x * np.cos(2*x) + 2.5 * x + 1.1}
# Plot the "centerline" with `plot`
ax.plot(x, mean, color=black, data=data_obj)
plt.show()
