画单个图的时候可以直接用plt.xxx,但是画多个子图的时候别一股脑的从头到尾plt.xxx了,可读性极差,而是要用plt.subplots()创建n行m列的子图,这个函数返回figure和坐标系列表axes,用axes来作图。
官网上有两张图介绍了matplotlib画出的一张figure的组成部分:
https://matplotlib.org/1.5.1/faq/usage_faq.html#parts-of-a-figure
https://matplotlib.org/tutorials/introductory/usage.html#sphx-glr-tutorials-introductory-usage-py
figure是整张画布,axes是这张画布中有多少个坐标系(即多个子图)
在了解了各部分的英文表达之后就能很清楚各个函数的用法了
这里给出一个示例:
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei'] #防止中文乱码
plt.rcParams['axes.unicode_minus']=False #防止负号乱码
fig, axes = plt.subplots(2,2) #创建包含2行2列子图的figure
x = ['横','轴','坐','标'] # x坐标不一定非得是数字,字符串也可以
y1 = [1,2,3,4]
y2 = [2,4,5,8]
# 在第一行第一列的子图中作图
axes[0,0].plot(x,y1,color='b',linestyle='--',marker='<',label='第一条线')
axes[0,0].plot(x,y2,color='tab:orange',linestyle='-.',marker='o',label='第二条线')
axes[0,0].legend() #显示legend
axes[0,0].set_xlabel('横轴')
axes[0,0].set_ylabel('纵轴')
axes[0,0].set_title('折线图')
x = np.arange(0,1,0.2)
y1 = x**2
y2 = x**3
# 在第二行第二列的子图中作图
axes[1,1].scatter(x,y1,color='r',marker='D',label='二次函数')
axes[1,1].scatter(x,y2,color='g',marker='1',label='三次函数')
axes[1,1].legend()
axes[1,1].set_xlabel('xlabel')
axes[1,1].set_ylabel('ylabel')
axes[1,1].set_title('散点图')
plt.savefig('a.png')
plt.show()
效果图:
常用API参考:
pyplot:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.html#module-matplotlib.pyplot
线和标记的颜色怎么表示:https://matplotlib.org/gallery/color/named_colors.html
marker用什么符号表示:https://matplotlib.org/api/markers_api.html#module-matplotlib.markers