python Matplotlib模塊的使用
一、Matplotlib簡介與安裝
Matplotlib也就是Matrix Plot Library,顧名思義,是Python的繪圖庫。它可與NumPy一起使用,提供了一種有效的MATLAB開源替代方案。它也可以和圖形工具包一起使用,如PyQt和wxPython。安裝方式:執行命令 pip install matplotlib一般常用的是它的子包PyPlot,提供類似MATLAB的繪圖框架。
二、使用方法
1.繪制一條直線 y = 3 * x + 4,其中 x 在(-2, 2),取100個點平均分布
# -*- coding: utf-8 -*-import matplotlib.pyplot as pltimport numpy as np# 創建數據x = np.linspace(-2, 2, 100)y = 3 * x + 4# 創建圖像plt.plot(x, y)# 顯示圖像plt.show()
2.在一張圖里繪制多個子圖
# -*- coding: utf-8 -*-import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.ticker import NullFormatter'''多個子圖'''# 為了能夠復現np.random.seed(1)y = np.random.normal(loc=0.5, scale=0.4, size=1000)y = y[(y > 0) & (y < 1)]y.sort()x = np.arange(len(y))plt.figure(1)# linear# 使用.subplot()方法創建子圖,221表示2行2列第1個位置plt.subplot(221)plt.plot(x, y)plt.yscale(’linear’)plt.title(’linear’)plt.grid(True)# logplt.subplot(222)plt.plot(x, y)plt.yscale(’log’)plt.title(’log’)plt.grid(True)# symmetric logplt.subplot(223)plt.plot(x, y - y.mean())plt.yscale(’symlog’, linthreshy=0.01)plt.title(’symlog’)plt.grid(True)# logitplt.subplot(224)plt.plot(x, y)plt.yscale(’logit’)plt.title(’logit’)plt.grid(True)plt.gca().yaxis.set_minor_formatter(NullFormatter())plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25, wspace=0.35)plt.show()
3.繪制一個碗狀的3D圖形,著色使用彩虹色
# -*- coding: utf-8 -*-import matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport numpy as np'''碗狀圖形'''fig = plt.figure(figsize=(8, 5))ax1 = Axes3D(fig)alpha = 0.8r = np.linspace(-alpha, alpha, 100)X, Y = np.meshgrid(r, r)l = 1. / (1 + np.exp(-(X ** 2 + Y ** 2)))ax1.plot_wireframe(X, Y, l)ax1.plot_surface(X, Y, l, cmap=plt.get_cmap('rainbow')) # 彩虹配色ax1.set_title('Bowl shape')plt.show()
4.更多用法
參見官網文檔
以上就是python Matplotlib模塊的使用的詳細內容,更多關于python Matplotlib模塊的資料請關注好吧啦網其它相關文章!
相關文章: