Python数据可视化分析 matplotlib教程

第一节课:
课程简介
plt.plot([1,2,3],[3,2,1])
plt.show()
第一个参数是所有的x坐标,第二个参数是所有的y坐标
第二节课:
numpy基本知识
第三节课:
matplotlib的基本用法
散点图的绘制方法:
plt.scatter(height, weight) # 第一个是所有的x,第二个是所有的y
外观参数:
颜色c、点的大小s(面积)、形状marker
官网 matplotlib.org
透明度alpha
第四节课:
折线图的画法
plt.plot(x_list, y_list)
第五节课:
条形图的画法
plt.bar(left=index, height=y) # left是条形图左边的坐标,height是条形图的高度
外观参数:color,width,orientation=’horizontal”(需要使用bottom,left改成0)
画层叠式的柱状图和并列式的柱状图

层叠图:修改bottom
第六节课:
直方图的画法
第七节课:饼状图的画法
第八节课:箱型图的画法
第九节课:颜色和样式
样式字符串:颜色点型线形

第十节课:三种编程方式
- pyplot:高层封装
- pylab,matplotlib+numpy
- 面向对象的方式,最底层
尝试三种方式:
- pylab
from pylab import *
plot(x,y)
title('pylab')
show()
2. pyplot
3. 面向对象的方式
fig = plt.figure() # 生成一个fig对象(画布)
ax=fig.add_subplot(111) # 坐标轴对象,画布上的坐标轴
l,=plt.plot(x,y)
t = ax.set_title("object oriented')
plt.show()
第十一节课:如何在同一张图上画多个子图
三个对象:
FigureCanvas 画布
Figure 图像
Axes 坐标轴
ax=fig.add_subplot(111) 行+列+位置
这是在figure上面添加axes的常用方法
fig=plt.figure()
ax1=fig.add_subplot(221)
ax1.plot(x,y)

ax2=fig_add_subplot(222)
...
plt.show()
除了面向对象的方式,pyplot也有画子图的函数
plt.subplot(221)参数含义和add_subplot()相同
第十二节课:如何生成多张图
fig1=plt.figure()
ax1=fig.add_subplot(111)
ax1.plot(x,y)
plt.show()
生成了一张图
fig2=plot.figure()
ax2=fig2.add_subplot(111)
ax2.plot(x,y)
生成了两张图
第十三节课:网格的画法
两种方法:plt封装的函数,面向对象的方法
- plt的函数
plt.plot(x,y)
plt.grid(True) # 打开网格
定制化网格:
plt.grid(color='r', linewidth='2', linestyle='-')
2. 面向对象的方法绘制网格
fig=plt.figure()
ax = fig.add_subplot(111)
plt.plot(x,y)
ax.grid(color=;g')
plt.show()
第十四节课:图例的画法
两种方法,plt和面向对象的方法
- plt的方法
plt.plot(x,y,label='normal')
plt.plot(x,y, label='Fase')
plt.legend()
图例的参数:
位置参数:location
plt.legend(loc=1) # 1,2,3,4四个角落

扁平化,第二个参数:ncol,有几列
plt.legend(ncol=3)
使用plt的另外一种画法:把label写道legend里面
plt.legend(['normal','fast','slow'])
2. 面向对象的方式
fig=plt.figure()
ax = fig.add_subplot(111)
l,=plt.plot(x,y)
第一个方法:
ax.legend(['ax legend'])
第二个方法:
l.set_label('label via method')
ax.legend()
第三个方法:
l,=plt.plot(x,y, label='inline label')
ax.legend()
第十五节课:坐标轴范围的调整
plt.axis([-5,5,20,60])#直接plt设置
plt.xlim([minx,maxx])
plt.ylim(...)
第十六节课:调整坐标轴的刻度
plt.plot(x,y)
ax=plt.gca() # 获取当前的坐标轴
ax.locator_params(nbins=10) # 坐标轴一共有多少格,可以指定x, ax.locator_params('x', nbins=10)
也可以使用plt.locator_params('x', nbins=10)来实现该功能
第十七节课:在一张图添加一个新的坐标轴
plt.plot(x,y)
plt.twinx() # 添加一个新的坐标轴
plt.plot(x,y2, 'r')
面向对象的方式:
ax1.plot(x,y)
ax1.set_ylabel('Y1')
ax2=ax1.twinx() # 生成另一个坐标轴
ax2.plot(x,y2,'r')
ax2.set_ylabel('Y2')
ax1.set_xlabel('compare Y1 and Y2')
plt.show()
第十八节课:添加注释符号
plt.plot(x,y)
plt.annotate("this is the comment", xy=(0,1),xytext=(0,20), arrowprops=dict(facecolor='r', frac=1, headwidth=10, width=10))
plt.show()

第十九节课:如何添加文字
plt.plot(x,y)
plt.text(0,40,'function: y=x*x')