1 plt.和ax.的区别
在matplotlib中,有两种画图方式:
plt.figure(): **plt.*系列。通过plt.xxx来画图,其实是取了一个捷径。这是通过matplotlib提供的一个api,这个plt提供了很多基本的function可以让你很快的画出图来,但是如果你想要更细致的精调,就要使用另外一种方法。
plt.figure(1)
plt.subplot(211)
plt.plot(A,B)
plt.show()
fig, ax = plt.subplots(): 这个就是正统的稍微复杂一点的画图方法了。指定figure和axes,然后对axes单独操作。
fig, ax = plt.subplots()
ax.plot(A,B)
2 名词解释
fig = plt.figure():Figure 可以解释为画布。画图的第一件事,就是创建一个画布figure,然后在这个画布上加各种元素。
ax = fig.add_subplot(1,1,1):Axes 类似于在画布里面的一个小图。ax 下可以修改编辑的变量非常多,基本上能包含所有需求。
ax.xaxis/ax.yaxis:Axis 坐标轴。
2.1 图像上的各个部分
3 画图
3.1 全局参数
通过rcParams()设置全局参数。
plt.rcParams['font.sans-serif'] = ['KaiTi']
plt.rcParams['font.serif'] = ['KaiTi']
plt.rcParams['axes.unicode_minus'] = False # 这句和字体没有关系,但很可能有人也会遇到保存图像是负号'-'显示为方块的问题,或者转换负号为字符串的问题,使用这个语句可以避免。
3.2 建立画布
有两种方式来建立画布。这两种方式都是建立一个大画布(figure),然后添加一个小画布(ax)。
fig = plt.figure()
ax = fig.add_subplot(2,2,1)
ax.plot([1,2,3])
fig = plt.figure()
ax = plt.subplot(2,2,1)
ax.plot([1,2,3])
还可以同时建立大画布和小画布,然后指定某一个小画布进行绘制。
fig, ax = plt.subplots(2,2)
ax1 = ax[0,0]
ax1.plot([0, 1, 2], [2, 4, 8])
fig = plt.figure()
ax = plt.subplot(231)
ax.plot([0, 1, 2], [0, 2, 4])
ax.set_title('1st fig')
ax.set_ylabel('y', rotation = 0)
# 数字格式
labels = ax.set_xticks([0,1,2,3])
#文字格式
labels = ax.set_xticklabels(('zero', 'one', 'two', 'three'), rotation=30, fontsize='small')
ax = plt.subplot(232)
ax.plot([0,10])
ax = plt.subplot(233)
ax = plt.subplot(234)
ax = plt.subplot(235)
ax = plt.subplot(236)
注意:
需要用字符来当作坐标标注(ticks)的时候,需要先使用数字格式的坐标标注,然后对应着指定字符。
比如如果不使用labels = ax.set_xticks([0,1,3,5])
这句,直接使用labels = ax.set_xticklabels(('zero', 'one', 'two', 'three'), rotation=30, fontsize='small')
那么图片就会出现下面这种情况。
发现横坐标的标注,从我们给定的列表中index = 1 的位置开始绘制了。
加上这两句labels = ax.set_xticks([0,1,2,3])
,labels = ax.set_xticklabels(('zero', 'one', 'two', 'three'), rotation=30, fontsize='small')
,就会出现下面的图像。
这一句中ax.set_xticks()
的坐标是真实的坐标,ax.set_xticklabels(('zero', 'one', 'two', 'three'))
这一句中的标签,对应上上面的真是坐标。
如果改写成labels = ax.set_xticks([0,1,3,6])
,labels = ax.set_xticklabels(('zero', 'one', 'two', 'three'), rotation=30, fontsize='small')
,则会出现下面的图象。
3.3 更精美的图
fig, ax = plt.subplots(figsize=(14,7))
# fig, ax = plt.subplots(2,1,figsize(14,7))# ax[0].***# ax[1].***
ax.plot(A,B, label = 'A')
ax.plot(B,A, label = 'B')
ax.set_title('Title',fontsize=18)
ax.set_xlabel('xlabel', fontsize=18, fontfamily = 'sans-serif', fontstyle='italic')
ax.set_ylabel('ylabel', fontsize='x-large', fontstyle='oblique')
ax.legend()
ax.set_aspect('equal')
ax.minorticks_on()
ax.set_xlim(0,16)
ax.grid(which='minor', axis='both')
ax.xaxis.set_tick_params(rotation=45,labelsize=18,colors='g')
start, end = ax.get_xlim()
print(start, end)
ax.xaxis.set_ticks(np.arange(start, end, 1))
ax.yaxis.tick_right()