python模块(5)-Matplotlib 简易使用教程
Matplotlib簡易使用教程
- 0.matplotlib的安裝
- 1.導入相關庫
- 2.畫布初始化
- 2.1 隱式創建
- 2.2 顯示創建
- 2.3 設置畫布大小
- 2.4 plt.figure()常用參數
- 3.plt. 能夠繪制圖像類型
- 3.1等高線
- 3.2 箭頭arrow
- 4.簡單繪制小demo
- demo1.曲線圖
- demo2-柱狀、餅狀、曲線子圖
- 5.plt.plot()--設置曲線顏色,粗細,線形,圖例
- 6.plt.xxx常用方法待更新
- 6.1 plt.text() 圖中添加文字
- 6.2 plt.xlim() 設置坐標軸的范圍
- 6.3 plt.savefig()存圖 參數詳解
- 6.4 xxx.title()設置標題
- 6.4.1 極簡設置
- 6.4.2 plt.title()常用的參數
- 6.5 plt.lengend()圖例
- 6.6 plt.xticks()改變坐標軸的刻度文字
- 7. matplotlib.colorbar
- 9.錯誤信息
- 9.1 RuntimeError: Invalid DISPLAY variable
- 10.Seaborn
- 11.Bokeh
Matplotlib 是 Python 的繪圖庫。 它可與 NumPy 一起使用,提供了一種有效的 MatLab 開源替代方案。其子庫pyplot包含大量與MatLab相似的函數調用接口。
matplotlib繪圖三個核心概念–figure(畫布)、axes(坐標系)、axis(坐標軸)
畫圖首先需要初始化(創建)一張畫布,然后再創建不同的坐標系,在各自的坐標系內繪制相應的圖線
繪圖步驟
導入相關庫->初始化畫布->準備繪圖數據->將數據添加到坐標系中->顯示圖像
注:可以繪制list,也可以繪制Numpy數組
0.matplotlib的安裝
Linux 終端安裝
pip install matplotlib
1.導入相關庫
import numpy as np
import matplotlib.pyplot as plt
2.畫布初始化
2.1 隱式創建
第一次調用plT.xxx(諸如:plt.plot(x,y))時,系統自動創建一個figure對象,并在figure上創建一個axes坐標系,基于此進行繪圖操作(隱式初始化只能繪制一張圖)
x=[1,2,5,7] y=[4,9,6,8] plt.plot(x,y) plt.show()2.2 顯示創建
手動創建一個figure對象,在畫布中添加坐標系axes
figure = plt.figure() axes1 = figure.add_subplot(2,1,1) Axes2= figure.add_subplot(2,1,2)2.3 設置畫布大小
figure = plt.figure(figsize=(xinch,yinch))
2.4 plt.figure()常用參數
畫布屬性(數量,大小)通過畫布初始化方法設置,在初始化的時候填寫響應的參數。
plt.figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, FigureClass=<class ‘matplotlib.figure.Figure’>, clear=False, **kwargs
0.num–a unique identifier for the figure (int or str)
1.figsize–畫布大小(default: [6.4, 4.8] in inches.)
2.dpi=None–The resolution of the figure in dots-per-inch.
3.facecolor–The background color
4.edgecolor–The border color
5.frameon–If False, suppress drawing the figure frame.
6.FigureClass=<class ‘matplotlib.figure.Figure’>,
7.clear=False, If True and the figure already exists, then it is cleared.
3.plt. 能夠繪制圖像類型
0.曲線圖:plt.plot()
1.散點圖:plt.scatter()
2.柱狀圖:plt.bar()
3.等高線圖:plt.contourf()
4.在等高線圖中增加label:plt.clabel()
5.矩陣熱圖:plt.imshow()
6.在隨機矩陣圖中增加colorbar:plt.colorbar()
7.直方圖
plt.hist( data,bin)
https://www.jianshu.com/p/f2f75754d4b3
隱式創建時,用plt.plot()在默認坐標系中添加數據,顯示創建時,用axes1.plot()在對應的坐標系中添加繪制數據 .plot()用于繪制曲線圖
3.1等高線
import matplotlib.pyplot as plt n=256 x=np.linspace(-3,3,n) y=np.linspace(-3,3,n) X,Y=np.meshgrid(x,y) #把X,Y轉換成網格數組,X.shape=nn,Y.shape=nn plt.contourf(X,Y,height(X,Y),8,alpha=0.75,cmap=plt.cm.hot) #8:8+2=10,將高分為10部分, #alpha:透明度 #cmap:color map #use plt.contour to add contour lines C=plt.contour(X,Y,height(X,Y),8,colors=“black”,linewidth=.5) #adding label plt.clabel(C,inline=True,fontsize=10) #clabel:cycle的label,inline=True表示label在line內,fontsize表示label的字體大小 plt.show()參考博文:https://cloud.tencent.com/developer/article/1544887
3.2 箭頭arrow
arrow_x1 = x_list[0]arrow_x2 = x_list[10]arrow_y1 = y_list[0]arrow_y2 = y_list[10]self.axis1.arrow(arrow_x1, arrow_y1, arrow_x2-arrow_x1, arrow_y2-arrow_y1, width=0.1, length_includes_head=True, head_width=1,head_length=3, fc='b',ec='b')參考文檔:matplotlib 畫箭頭的兩種方式
4.簡單繪制小demo
demo1.曲線圖
import numpy as np import matplotlib.pyplot as plt figure = plt.figure() axes1 = figure.add_subplot(2,1,1) # 2*1 的 第2個圖 axes2= figure.add_subplot(2,1,2) # 2*1 的 第2個圖 # axes1 = figure.add_subplot(2,2,1) 2*2 的 第1個圖 x,y=[1,3,5,7],[4,9,6,8] a,b=[1,2,4,5],[8,4,6,2] axes1.plot(x,y) Axes2.plor(a,b)plot.show() # 顯示圖像 path = "xxx/xxx/xxx.png" plt.savefig(path) #保存圖像 plt.close() # 關閉畫布demo2-柱狀、餅狀、曲線子圖
# 20210406 import matplotlib.pylab as plt import numpy as np# 1.柱狀圖 plt.subplot(2,1,1) n = 12 X = np.arange(n) Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n) Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)plt.bar(X, +Y1, facecolor="#9999ff", edgecolor="white") plt.bar(X, -Y2, facecolor="#ff9999", edgecolor="white")# 利用plt.text 指定文字出現的坐標和內容 for x, y in zip(X,Y1):plt.text(x+0.4, y+0.05, "%.2f" % y, ha="center", va="bottom") # 限制坐標軸的范圍 plt.ylim(-1.25, +1.25)# 2.餅狀圖 plt.subplot(2,2,3) n = 20 Z = np.random.uniform(0, 1, n) plt.pie(Z)# 3.第三部分 plt.subplot(2, 2, 4) # 等差數列 X = np.linspace(-np.pi, np.pi, 256, endpoint=True) Y_C, Y_S = np.cos(X), np.sin(X)plt.plot(X, Y_C, color="blue", linewidth=2.5, linestyle="-") plt.plot(X, Y_S, color="red", linewidth=2.5, linestyle="-")# plt.xlim-限定坐標軸的范圍,plt.xticks-改變坐標軸上刻度的文字 plt.xlim(X.min() * 1.1, X.max() * 1.1) plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],[r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$\pi$"]) plt.ylim(Y_C.min()*1.1, Y_C.max()*1.1) plt.yticks([-1, 0, 1],[r"$-1$", r"$0$", r"$+1$"]) #plt.show() plt.savefig("test.png")5.plt.plot()–設置曲線顏色,粗細,線形,圖例
plt.plot(x,y,color=“deeppink”,linewidth=2,linestyle=’:’,label=‘Jay income’, marker=‘o’)
參數含義:
0–x,y :array 表示 x 軸與 y 軸對應的數據
1–color :string 表示折線的顏色; None
2–label :string 數據圖例內容:label=‘實際數據’ None,配合plt.legend()使用
3–linestyle :string 表示折線的類型;
4–marker :string 表示折線上數據點處的類型; None
5–linewidth :數值 線條粗細:linewidth=1.=5.=0.3 1
6–alpha :0~1之間的小數 表示點的透明度; None
注:label:配合 plt.legend()使用,legend(…, fontsize=20),可以設置圖例的字號大小
https://www.cnblogs.com/shuaishuaidefeizhu/p/11361220.html
6.plt.xxx常用方法待更新
grid 背景網格
tick 刻度
axis label 坐標軸名稱
tick label 刻度名稱
major tick label 主刻度標簽
line 線style 線條樣式
marker 點標記
font 字體相關
annotate標注文字:https://blog.csdn.net/helunqu2017/article/details/78659490/
6.1 plt.text() 圖中添加文字
plt.text(x, y, s, fontdict=None, withdash=False, **kwargs)
可以用來給線上的sian打標簽/標注
| x y | :scalars 放置text的位置,途中的橫縱坐標位置 |
| s | :str 要寫的內容text |
| fontdict | : dictionary, optional, default: None 一個定義s格式的dict |
| withdash | : boolean, optional, default: False。如果True則創建一個 TextWithDash實例。 |
| color | 控制文字顏色 |
借助 transform=ax.transAxes,text 標注在子圖相對位置
# 設置文本,目標位置 左上角,距離 Y 軸 0.01 倍距離,距離 X 軸 0.95倍距離 ax.text(0.01, 0.95, "test string", transform=ax.transAxes, fontdict={'size': '16', 'color': 'b'})其他參數參考博文:https://blog.csdn.net/The_Time_Runner/article/details/89927708
6.2 plt.xlim() 設置坐標軸的范圍
畫布坐標軸設置
plt.xlim((-5, 5))
plt.ylim((0,80))
子圖坐標軸配置
Axes.set_xlim((-5,5))
Axes.set_ylim((0,80))
問題1:橫縱坐標等比例
plt.axis(“equal”)
Plt.axis(“scaled”) # 坐標值標的很小,曲線出描繪框架
6.3 plt.savefig()存圖 參數詳解
將繪制圖像以png的形式存在當前文件夾下:
plt.savefig(“test.png”)
通過函數參數控制文件的存儲格式,存儲路徑
savefig(fname, dpi=None, facecolor=’w’, edgecolor=’w’,
orientation=’portrait’, papertype=None, format=None,
transparent=False, bbox_inches=None, pad_inches=0.1,
frameon=None)
0–fname:A string containing a path to a filename, or a Python file-like object, or possibly some backend-dependent object such as PdfPages.(保存圖片位置與路徑的字符串)
1–dpi: None | scalar > 0 | ‘figure’
2–facecolor, edgecolor:(?)
3–orientation: ‘landscape’ | ‘portrait’
4–papertype:
5–format:(png, pdf, ps, eps and svg)
6–transparent:
7–frameon:
8–bbox_inches:
9–pad_inches:
10–bbox_extra_artists:
plt.show() 是以圖片阻塞的方式顯示圖片,只有關掉顯示窗口,代碼才會繼續運行。可以選擇將圖片保存下來(記得設置容易識別的文件名)查看,來保障程序運行的流暢性,
注:存完圖關閉畫布,防止內存占滿
plt.close()
過多畫布占內存報錯
RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (matplotlib.pyplot.figure) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam figure.max_open_warning).
max_open_warning, RuntimeWarning)
6.4 xxx.title()設置標題
6.4.1 極簡設置
1.隱式初始化(畫布)圖像標題設置
plt.title(‘Interesting Graph’,fontsize=‘large’)
2.顯式初始化(子圖/坐標系)圖像標題設置
ax.set_title(‘title test’,fontsize=12,color=‘r’)
3.設置畫布標題
figure.suptitle(“xxxx”)
6.4.2 plt.title()常用的參數
0.fontsize–設置字體大小,默認12,可選參數 [‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’,‘x-large’, ‘xx-large’]
1.fontweight–設置字體粗細,可選參數 [‘light’, ‘normal’, ‘medium’, ‘semibold’, ‘bold’, ‘heavy’, ‘black’]
2.fontstyle–設置字體類型,可選參數[ ‘normal’ | ‘italic’ | ‘oblique’ ],italic斜體,oblique傾斜
3.verticalalignment–設置水平對齊方式 ,可選參數 : ‘center’ , ‘top’ , ‘bottom’ ,‘baseline’
4.horizontalalignment–設置垂直對齊方式,可選參數:left,right,center
5.rotation–(旋轉角度)可選參數為:vertical,horizontal 也可以為數字
6.alpha–透明度,參數值0至1之間
7.backgroundcolor–標題背景顏色
8.bbox–給標題增加外框 ,常用參數如下:
9.boxstyle–方框外形
10.facecolor–(簡寫fc)背景顏色
11.edgecolor–(簡寫ec)邊框線條顏色
12.edgewidth–邊框線條大小
參考鏈接–https://blog.csdn.net/helunqu2017/article/details/78659490/
6.5 plt.lengend()圖例
from matplotlib import pyplot as plt import numpy as nptrain_x = np.linspace(-1, 1, 100) train_y_1 = 2*train_x + np.random.rand(*train_x.shape)*0.3 train_y_2 = train_x**2+np.random.randn(*train_x.shape)*0.3 p1 = plt.scatter(train_x, train_y_1, c='red', marker='v' ) p2= plt.scatter(train_x, train_y_2, c='blue', marker='o' ) legend = plt.legend([p1, p2], ["CH", "US"], facecolor='blue')# 省略[p1, p2] 直接寫圖例 plt.show()6.6 plt.xticks()改變坐標軸的刻度文字
plt.xticks([-np.pi, -np.pi/2, np.pi/2, np.pi],[r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$\pi$"])7. matplotlib.colorbar
plt.colorbar()
fig.colorbar(norm=norm, cmap=cmp ax=ax) # norm色卡數字范圍,cmap 調制顏色
https://blog.csdn.net/sinat_32570141/article/details/105345725
9.錯誤信息
9.1 RuntimeError: Invalid DISPLAY variable
在遠端服務器上運行時報錯,本地運行并沒有問題
原因:matplotlib的默認backend是TkAgg,而FltAgg、GTK、GTKCairo、TkAgg、Wx和WxAgg這幾個backend都要求有GUI圖形界面,所以在ssh操作的時候會報錯。
解決:在導入matplotlib的時候指定不需要GUI的backend(Agg、Cairo、PS、PDF和SVG)。
import matplotlib.pyplot as plt
plt.switch_backend(‘agg’)
10.Seaborn
Seaborn是一種基于matplotlib的圖形可視化python libraty。它提供了一種高度交互式界面,便于用戶能夠做出各種有吸引力的統計圖表。
參考資料
https://baijiahao.baidu.com/s?id=1659039367066798557&wfr=spider&for=pc
https://www.kesci.com/home/column/5b87a78131902f000f668549
https://blog.csdn.net/gdkyxy2013/article/details/79585922
11.Bokeh
針對瀏覽器中圖形演示的交互式繪圖工具。目標是使用d3.js樣式(不懂)提供的優雅,簡潔新穎的圖形風格,同時提供大型數據集的高性能交互功能。
他提供的交互式電影檢索工具蠻吸引我的吼,并打不開這個網址,😭。
http://demo.bokehplots.com/apps/movies
Python學習筆記(4)——Matplotlib中的annotate(注解)的用法
matplotlib xticks用法
matplotlib.pyplot 標記出曲線上最大點和最小點的位置
matplotlib 中子圖subplot 繪圖時標題重疊解決辦法(備忘)
總結
以上是生活随笔為你收集整理的python模块(5)-Matplotlib 简易使用教程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 大数据学习(5)-- NoSQL数据库
- 下一篇: 《Python Cookbook 3rd