3 Matplotlib
3.1 figure、axes、axis
ax1 = plt.subplot(221)
ax2 = plt.subplot(222)
ax3 = plt.subplot(223)
ax4 = plt.subplot(224)
plt.show()
由上图可以看出,figure是一个画布,一个画布上可以画多个坐标系(axes),每个(二维)坐标系有两个轴(axis),相信大家看到上图就能够知道画布,坐标系和坐标轴三者之间的关系。
3.2 图像布局
3.2.1 plt.subplot()
上例中使用的也是一种图像布局的方法,将一个画布分成四个部分,将四个坐标系分别命名成ax1,ax2,ax3,ax4
3.2.2 plt.subplots()
fig,ax=plt.subplots(2,2)
ax[0,0].plot([1,2,3],[1,2,3])
ax[0,1].scatter([1,2,3],[1,2,3])
ax[1,0].bar([1,2,3],[1,2,3])
ax[1,1].pie([10,20,30])
plt.show()
3.3 折线图-plt.plot()
面向对象制图
fig = plt.figure(figsize=(8,6))
axes = fig.add_subplot()
axes.plot([0,1,2,3,4,5], [1,2,4,6,8,9],c='r',ls=':',marker='o',markersize='10',mec='b',mfc='y')
axes.plot([1,3],c='b',ls='-.')
axes.plot([1,4],c='g',ls='--')
axes.plot([1,5],c='y',ls='-')
axes.grid(True,color='r', linestyle='-', linewidth=2, alpha=0.2)
axes.set_xmargin(0)
axes.set_ymargin(0)
plt.show()
使用循环画多个图
fig = plt.figure(figsize=(8,6))
config = {
'c':['r','g','b','y'],
'ls':['-','-.','--',':'],
'lw':[1,2,3,4],
}
ax = fig.add_subplot()
for i in range(4):
ax.plot([1,i+2],c=config['c'].pop(),ls=config['ls'].pop(),lw=config['lw'].pop())
plt.show()
> 常用参数说明
xdata,ydata :
c or color :
============= ===============================
character color
============= ===============================
``'b'`` blue
``'g'`` green
``'r'`` red
``'c'`` cyan
``'m'`` magenta
``'y'`` yellow
``'k'`` black
``'w'`` white
============= ===============================
linestyle or ls :
============= ===============================
character description
============= ===============================
``'-'`` solid line style
``'--'`` dashed line style
``'-.'`` dash-dot line style
``':'`` dotted line style
============= ===============================
linewidth or lw :
marker :
============= ===============================
character description
============= ===============================
``'.'`` point marker
``','`` pixel marker
``'o'`` circle marker
``'v'`` triangle_down marker
``'^'`` triangle_up marker
``'<'`` triangle_left marker
``'>'`` triangle_right marker
``'1'`` tri_down marker
``'2'`` tri_up marker
``'3'`` tri_left marker
``'4'`` tri_right marker
``'8'`` octagon marker
``'s'`` square marker
``'p'`` pentagon marker
``'P'`` plus (filled) marker
``'*'`` star marker
``'h'`` hexagon1 marker
``'H'`` hexagon2 marker
``'+'`` plus marker
``'x'`` x marker
``'X'`` x (filled) marker
``'D'`` diamond marker
``'d'`` thin_diamond marker
``'|'`` vline marker
``'_'`` hline marker
============= ===============================
markeredgecolor or mfc :
markeredgewidth or mew: float
markerfacecolor or mfc: color
markersize or ms: float
markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool]
fmt = '[marker][line][color]'
3.4 散点图-plt.scatter()
fig = plt.figure()
ax = fig.add_subplot()
ax.scatter(x=np.random.randn(50),y=np.random.randn(50),s=np.random.randint(0,100,50),c=np.random.randn(50),marker='*')
plt.show()
3.5 柱状图-plt.bar()
垂直柱状图
plt.rcParams['font.sans-serif'] = "SimHei"
fig = plt.figure()
ax = fig.add_subplot()
x = ['裤子','上衣','袜子']
y1 = [14,20,23]
y2 = [17,19,32]
ax.bar(
x=x,
height=y1,
width=0.2,
align='center',
bottom=0,
color = 'b',
edgecolor = 'y',
linewidth = 5,
)
ax.set_label('男生')
ax.bar(
x=x,
height=y2,
width=0.2,
align='center',
bottom=y1,
color = 'r',
edgecolor = 'y',
linewidth = 5,
)
ax.set_label("女生")
ax.legend(["男","女"])
plt.show()
横向柱状图
plt.rcParams['font.sans-serif'] = "SimHei"
fig = plt.figure()
ax = fig.add_subplot()
x = ['裤子','上衣','袜子']
y1 = [14,20,23]
ax.barh(y=x,width=y1,height=0.8,left=[0,0,5])
ax.legend("销量")
plt.show(
直方图
hz,bins = np.histogram(np.random.randint(1,100,5000),bins=np.linspace(0,100,100))
hz,bins
plt.bar(x=bins[:-1],height=hz)
3.6 饼状图-plt.pie()
plt.rcParams['font.sans-serif'] = "SimHei"
fig = plt.figure()
ax = fig.add_subplot()
ax.pie(x=[12,45,23],explode=np.array([0,0,0.2]),labels=list("中美日"),colors=list('rgb'),autopct='%1.1f%%',shadow=True)
plt.show()
3.7 fontdict
{'fontsize': rcParams['axes.titlesize'],
'fontweight': rcParams['axes.titleweight'],
'color': rcParams['axes.titlecolor'],
'verticalalignment': 'baseline',
'horizontalalignment': loc}
附件0 综合练习
x = np.arange(-5,6,1)
y = 2*x + 5
fig, ax = plt.subplots(1,1)
ax.set_title("Test Axes",fontdict={'size':16,'color':'b'})
ax.spines['right'].set_color(None)
ax.spines['top'].set_color(None)
ax.set_xlim(-5,+5)
ax.set_xticks(np.arange(-5,6,1))
ax.set_ylim(-20,+20)
ax.set_xlabel('X',loc='right')
ax.set_ylabel('y',loc='top')
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))
ax.annotate('$y=2x+5$',xy=(3,16))
ax.scatter(x=(-5/2),y=0,c='b')
ax.scatter(x=0,y=5,c='b')
ax.scatter(x=2,y=9,c='b')
plt.scatter(x=(2,)*10,y=np.linspace(0,9,10),s=1,c='b')
plt.scatter(x=np.linspace(0,2,10),y=(9,)*10,s=1,c='b')
ax.plot(x,y)
plt.show()
如下图所示
附件1 所有配置项
plt.rcParams.keys()
附件2 常用配置项
plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False
plt.rcParams['savefig.dpi'] = 300
plt.rcParams['figure.dpi'] = 300
plt.rcParams['figure.figsize'] = (8.0, 4.0)
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
结语
|