![](https://img.haomeiwen.com/i15736132/c1ef31da207b8aee.png)
这一篇Matplotlib的教程会向大家介绍一些基本的作图语句。对于每一个搞数据分析的人来说,数据可视化是基本技能之一,可视化质量的高低会影响到最终的展示效果。
作为每一个利用Python来进行数据处理的人,Matplotlib必然是入门的第一件法宝。但是对于大多数刚入门的同学来说,Matplotlib内容过多,不知道该如何有效的入手,这里我们为大家总结了一些最常用的语句。
本文含有大量代码,建议使用大屏幕设备阅读
建立图像
import matplotlib.pyplot as plt
# 创建figure
fig = plt.figure()
fig2 = plt.figure(figsize=plt.figaspect(2.0))
# 定义/添加axis
fig.add_axes()
ax1 = fig.add_subplot(221)
ax3 = fig.add_subplot(212)
fig3, axes = plt.subplots(nrows=2,ncols=2)
fig4, axes2 = plt.subplots(ncols=3)
1D图像
# 由多个点连成的线
lines = ax.plot(x,y)
# 散点图
ax.scatter(x,y)
# 竖直方向的矩阵
axes[0,0].bar([1,2,3],[3,4,5])
# 水平方向的矩阵
axes[1,0].barh([0.5,1,2.5],[0,1,2])
# 水平方向且穿过坐标轴的直线
axes[1,1].axhline(0.45)
# 竖直方向且穿过坐标轴的直线
axes[0,1].axvline(0.65)
# 填色多边形
ax.fill(x,y,color='blue')
# 在y与0之间填色
ax.fill_between(x,y,color='yellow')
2D图像
fig, ax = plt.subplots() im = ax.imshow(img, cmap='gist_earth', interpolation='nearest',vmin=-2, vmax=2)
# 2D伪色图
axes2[0].pcolor(data2)
# 2D伪色图
axes2[0].pcolormesh(data)
# 等高线图
CS = plt.contour(Y,X,U)
# 填色等高线图
axes2[2].contourf(data1)
# 为等高线图添加标签
axes2[2]= ax.clabel(CS)
向量
# 指向坐标轴的箭头
axes[0,1].arrow(0,0,0.5,0.5)
# 2D箭头
axes[1,1].quiver(y,z)
# 2D向量域
axes[0,1].streamplot(X,Y,U,V)
数据分布图
# 直方图
ax1.hist(y)
# 箱型图
ax3.boxplot(y)
# 小提琴图
ax3.violinplot(z)
颜色相关指令
plt.plot(x, x, x, x**2, x, x**3)
ax.plot(x, y, alpha = 0.4)
ax.plot(x, y, c='k')
fig.colorbar(im, orientation='horizontal')
im = ax.imshow(img, cmap='seismic')
添加标记
fig, ax = plt.subplots() ax.scatter(x,y,marker=".")
ax.plot(x,y,marker="o")
线段风格
plt.plot(x,y,linewidth=4.0)
plt.plot(x,y,ls='solid')
plt.plot(x,y,ls='--')
plt.plot(x,y,'--',x**2,y**2,'-.')
plt.setp(lines,color='r',linewidth=4.0)
文本及注解
ax.text(1, -2.1, 'Example Graph', style='italic')
ax.annotate("Sine", xy=(8, 0), xycoords='data', xytext=(10.5, 0),textcoords='data', arrowprops=dict(arrowstyle="->", connectionstyle="arc3"))
#数学符号
plt.title(r'$sigma_i=15$', fontsize=20)
坐标轴、图例及布局
# 坐标轴边界
ax.margins(x=0.0,y=0.1)
ax.axis('equal')
ax.set(xlim=[0,10.5],ylim=[-1.5,1.5])
ax.set_xlim(0,10.5)
# 图例
ax.set(title='An Example Axes', ylabel='Y-Axis', xlabel='X-Axis')
ax.legend(loc='best')
# 坐标轴标点
ax.xaxis.set(ticks=range(1,5), Manually set x-ticks, ticklabels=[3,100,-12,"foo"])
ax.tick_params(axis='y', direction='inout', length=10)
# Subplot Spacing
fig3.subplots_adjust(wspace=0.5, hspace=0.3, left=0.125, right=0.9, top=0.9, bottom=0.1)
fig.tight_layout()
# 坐标轴设置
ax1.spines['top'].set_visible(False)
ax1.spines['bottom'].set_position(('outward',10))
显示及保存图像
# 保存图像
plt.savefig('foo.png')
# 展示图像
plt.show()
# 清空坐标轴
plt.cla()
# 清空整个Figure
plt.clf()
# 关闭图像窗口
plt.close()
总结一下,利用Matplotlib作图主要分为以下几个步骤:
1、数据准备
2、创建图像
3、作图
4、自定义图像
5、保存图像
6、展示图像
举例如下:
import matplotlib.pyplot as plt
# 准备数据
x = [1,2,3,4]
y = [10,20,25,30]
# 创建图像
fig = plt.figure()
ax = fig.add_subplot(111)
# 作图
ax.plot(x, y, color='lightblue', linewidth=3)
ax.scatter([2,4,6], [5,15,25], color='darkgreen', marker='^')
# 自定义图像
ax.set_xlim(1, 6.5)
# 保存图像
plt.savefig('foo.png')
# 展示图像
plt.show()
想成为一名合格的数据科学家/AI工程师吗?关注“机器学习学社”获取每天一份的新鲜咨询,为你开拓属于你自己的AI之路
网友评论