matplotlib安装和学习
安装:
根据python版本和操作系统版本下载对应的matplotlib。下载地址:https://sourceforge.net/projects/matplotlib/files/matplotlib/
我的电脑是win7(32bit),python是2.7,下载对应的matplotlib-1.5.1里面的matplotlib-1.5.1-cp27-none-win32.whl。利用python的pip包管理工具,直接在cmd窗口中cd到刚才下载文件的目录下,并输入以下命令:pip install matplotlib-1.5.1-cp27-none-win32.whl,直到安装完毕。
当安装完成后,利用在python的shell环境了,利用import matplotlib检测一下是否成功安装。
若在检测时,发现有错误,可能是缺少对应的模块,或者是安装的matplotlib的版本不够新,重新下载对应的matplotlib版本并重新安装。
学习:
学习的例子:http://matplotlib.org/examples/index.html
画图的命令:http://matplotlib.org/api/pyplot_summary.html
选择一个barchart例子,修改并加上一些注释的代码如下:
# -*- coding:utf-8 -*-
import numpy
import matplotlib.pyplot as plt
def draw():
starts = (10,5,8,20,7,12,8)
ends = (2,4,7,2,10,3,15)
N = len(starts)
ID_Name = ('1991','1992','1993','1994','1995','1996','1997')
ind = numpy.arange(N)#设置batchart的x位置
print ind
width = 0.35
fig,ax = plt.subplots()
rects1 = ax.bar(ind+width,starts,width,color = 'r')#rects1 represents starts data of each item
rects2 = ax.bar(ind+width+width,ends,width,color = '#38B0DE')#rects1 represents ends data of each item
ax.set_ylabel('Number')
ax.set_title('Index of 1991-1997')
ax.set_xlabel('Year')
ax.set_xticks(ind+width+width)#x的标签位置
ax.set_xticklabels(ID_Name)#为x设置标签
ax.legend((rects1[0],rects2[0]),('Start','End'))#加入图注
ymin, ymax = plt.ylim()#获取当前坐标系的纵坐标的极限坐标
xmin, xmax = plt.xlim()#获取当前坐标系的横坐标的极限坐标
plt.ylim(ymin,ymax+2)#设置并调整当前坐标系的纵坐标的极限坐标
plt.xlim(xmin+0.1,xmax-0.7)#设置并调整当前坐标系的横坐标的极限坐标
# 为每个barchart内的bar标注具体的信息
for rect in rects1:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()/2., 1.0*height,
'%d' % int(height),
ha='center', va='bottom')
for rect in rects2:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()/2., 1.0*height,
'%d' % int(height),
ha='center', va='bottom')
handle = plt.gcf()#获取当前窗口get current figure
handle.savefig('travelplot.png',format = 'png',dpi=100)#用png格式保存图片
plt.show()#显示图片
plt.close()#如果不关闭,后面的程序:print语句不会执行
print 'This sentence maybe does not appear when current figure does not close properly'
if __name__ == "__main__":
draw()
最终的效果图: