1 4

matplotlib模块学习笔记

Python有很多可视化工具,matplotlib是其中重要的一个。

matplotlib API函数都位于matplotlib.pyplot模块中,其通常的引入约定是:

import matplotlib.pyplot as plt
matplotlib的图像都位于Figure对象中,创建新的Figure方法为:
fig = plt.figure()

绘图不能直接在空Figure上,需要用add_subplot创建一个或多个subplot:

ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(2,2,3)

参数的意思是图像是 2x2 的,当前选中的是4个subplot中的第n个

当需要创建多个subplot时,有更为简单方便的方法,参数sharex,sharey表示制定的多个subplot具有相同的X轴和Y轴:

fig, axes = plt.subplots(2,3,sharex=True,sharey = True)

调整subplot周围的间距:

plt.subplots_adjust(wspace = 0,hspace = 0)

设置绘图的颜色、线型和标记(数据点):plot函数接收一组x和y坐标,还可以接收一个表示线型、颜色和标记的字符串缩写

ax.plot(x,y,'go--')

上面的例子中:g表示颜色,o表示标记,--表示线型,标记类型和线型必须放在颜色后面

设置刻度、标签和图例:设置x轴刻度

ax.set_xticks([0,250,500,750,1000])

设置x轴名称:

ax.set_xlabel('Stage')

设置图片标题:

ax.set_title('My first matplotlib plot')

添加图例:传入label参数

ax.plot(randn(1000).cumsum(),'k',label = 'one')
ax.plot(randn(1000).cumsum(),'k--',label = 'two')
ax.plot(randn(1000).cumsum(),'k.',label = 'three')
ax.legend()

最后,需要将图片显示出来:

plt.show()

 

 

posted @ 2017-09-24 22:24  韦木三  阅读(844)  评论(0编辑  收藏  举报