python數據分析scipy和matplotlib(三)


Scipy

  • 在numpy基礎上增加了眾多的數學、科學及工程常用的庫函數;
  • 線性代數、常微分方程求解、信號處理、圖像處理、稀疏矩陣等;

 

Matplotlib

  • 用於創建出版質量圖表的繪圖工具庫;
  • 目的是為python構建一個Matlab式的繪圖接口;
  • import matplotlib.pyplot as plt,pyplot模塊包含了常用的matplotlib API函數;
  • figure, Matplotlib的圖像均位於figure對象中;
  • subplot,figure.add_subplot(a,b,c),a、b表示分割成a*b的區域,c表示當前選中要操作的區域(從1開始編號);
# 引入matplotlib包
import matplotlib.pyplot as plt
# 創建figure
fig = plt.figure()

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

# 在subplot上作圖
import numpy as np

random_arr = np.random.randn(100)
#print random_arr

# 默認是在最后一次使用subplot的位置上作圖
plt.plot(random_arr)
plt.show()
  • 執行結果:

說明:figure.add_subplot(a,b,c)返回的是AxesSubplot對象,plot繪圖的區域是最后一次指定subplot的位置。

 

subplot結合scipy繪制統計圖

  • 正態分布,scipy.stats.norm.pdf
  • 正態直方圖,scipy.stats.norm.rvs
import scipy as sp
from scipy import stats
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-5, 15, 50)
# print x.shape

# 繪制高斯分布
plt.plot(x, sp.stats.norm.pdf(x=x, loc=5, scale=2))

# 疊加直方圖
plt.hist(sp.stats.norm.rvs(loc=5, scale=2, size=200), bins=50, normed=True, color='red', alpha=0.5)
plt.show()
  • 執行結果:

 

subplot直方圖hist

# 繪制直方圖
import matplotlib.pyplot as plt
import numpy as np
plt.hist(np.random.randn(100), bins=10, color='b', alpha=0.3)
plt.show()

 參數:np.random.randn(100) 生成隨機100個數據,bins分成10組,color顏色為blue藍色,alpha為透明度

subplot散點圖scatter

import matplotlib.pyplot as plt
import numpy as np
# 繪制散點圖
x = np.arange(50)
y = x + 5 * np.random.rand(50)
plt.scatter(x, y)
plt.show()

subplot柱狀圖bar

import matplotlib.pyplot as plt
import numpy as np
# 柱狀圖
x = np.arange(5)
y1, y2 = np.random.randint(1, 25, size=(2, 5))
width = 0.25
ax = plt.subplot(1,1,1)
ax.bar(x, y1, width, color='r')
ax.bar(x+width, y2, width, color='g')
ax.set_xticks(x+width)
ax.set_xticklabels(['a', 'b', 'c', 'd', 'e'])
plt.show()

subplot矩陣繪圖

import matplotlib.pyplot as plt
import numpy as np
m = np.random.rand(10,10)
plt.imshow(m, interpolation='nearest', cmap=plt.cm.ocean)
plt.colorbar()
plt.show()

plt.subplot()

同時返回新創建的figure和subplot對象數組

import matplotlib.pyplot as plt
import numpy as np
fig, subplot_arr = plt.subplots(2,2)
subplot_arr[0,0].hist(np.random.randn(100), bins=10, color='b', alpha=0.3)
plt.show()

 

學習參考

Matplotlib示例庫 http://matplotlib.org/gallery.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM