Python數(shù)據(jù)可視化分析 matplotlib教程

第一節(jié)課:
課程簡介
plt.plot([1,2,3],[3,2,1])
plt.show()
第一個參數(shù)是所有的x坐標,第二個參數(shù)是所有的y坐標
第二節(jié)課:
numpy基本知識
第三節(jié)課:
matplotlib的基本用法
散點圖的繪制方法:
plt.scatter(height, weight) # 第一個是所有的x,第二個是所有的y
外觀參數(shù):
顏色c、點的大小s(面積)、形狀marker
官網(wǎng) matplotlib.org
透明度alpha
第四節(jié)課:
折線圖的畫法
plt.plot(x_list, y_list)
第五節(jié)課:
條形圖的畫法
plt.bar(left=index, height=y) # left是條形圖左邊的坐標,height是條形圖的高度
外觀參數(shù):color,width,orientation=’horizontal”(需要使用bottom,left改成0)
畫層疊式的柱狀圖和并列式的柱狀圖

層疊圖:修改bottom
第六節(jié)課:
直方圖的畫法
第七節(jié)課:餅狀圖的畫法
第八節(jié)課:箱型圖的畫法
第九節(jié)課:顏色和樣式
樣式字符串:顏色點型線形

第十節(jié)課:三種編程方式
- 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()
第十一節(jié)課:如何在同一張圖上畫多個子圖
三個對象:
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也有畫子圖的函數(shù)
plt.subplot(221)參數(shù)含義和add_subplot()相同
第十二節(jié)課:如何生成多張圖
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)
生成了兩張圖
第十三節(jié)課:網(wǎng)格的畫法
兩種方法:plt封裝的函數(shù),面向對象的方法
- plt的函數(shù)
plt.plot(x,y)
plt.grid(True) # 打開網(wǎng)格
定制化網(wǎng)格:
plt.grid(color='r', linewidth='2', linestyle='-')
2. 面向對象的方法繪制網(wǎng)格
fig=plt.figure()
ax = fig.add_subplot(111)
plt.plot(x,y)
ax.grid(color=;g')
plt.show()
第十四節(jié)課:圖例的畫法
兩種方法,plt和面向對象的方法
- plt的方法
plt.plot(x,y,label='normal')
plt.plot(x,y, label='Fase')
plt.legend()
圖例的參數(shù):
位置參數(shù):location
plt.legend(loc=1) # 1,2,3,4四個角落

扁平化,第二個參數(shù):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()
第十五節(jié)課:坐標軸范圍的調整
plt.axis([-5,5,20,60])#直接plt設置
plt.xlim([minx,maxx])
plt.ylim(...)
第十六節(jié)課:調整坐標軸的刻度
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)來實現(xiàn)該功能
第十七節(jié)課:在一張圖添加一個新的坐標軸
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()
第十八節(jié)課:添加注釋符號
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()

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