14_面向对象API绘图、图中图 (A Plot inside of Another Plot)、设定绘图范围Setting the Plot Range、对数尺度Logarithmic Scale
14.面向對象API繪圖
14.1.圖中圖 (A Plot inside of Another Plot)
14.2.設定繪圖范圍 (Setting the Plot Range)
14.3.對數尺度(Logarithmic Scale)
14.面向對象API繪圖
Matplotlib繪圖庫的操作是通過API實現的,一種操作方法是類似MATLAB的函數接口的API;另一種操作方法是面向對象的API。這兩種API可以并行使用,不過函數接口的API的易用性明顯好于面向對象的API。
就像Python本身一樣,Matplotlib是以面向對象的方式編程和設計的。當使用多個圖形時,或者當一個圖形由多個子圖組成時,使用圖形對象方法的優點就會顯現出來。
在下面的示例中,我們以面向對象的方式創建一個繪圖。首先創建一個新的figure實例。將其引用存儲在一個Figure類實例,即變量figure實例。將其引用存儲在一個Figure類實例,即變量fig中。然后,我們fig中使用add_axes方法創建一個新的軸的實例。
import numpy as np import matplotlib.pyplot as plt fig = plt.figure() X = np.arange(0,10) Y = np.random.randint(1, 20, size=10) left, bottom, width, height = 0.1, 0.1, 0.8, 0.8 axes = fig.add_axes([left, bottom, width, height]) axes.plot(X, Y, 'b') axes.set_xlabel('x') axes.set_ylabel('y') axes.set_title('title') plt.show()在不使用figure實例的情況下,代碼如下所示:
import numpy as np import matplotlib.pyplot as plt fig = plt.figure() X = np.arange(0,10) Y = np.random.randint(1, 20, size=10) left, bottom, width, height = 0.1, 0.1, 0.8, 0.8 axes = fig.add_axes([left, bottom, width, height]) axes.plot(X, Y, 'b') axes.set_xlabel('xxxxxxxxxxxxx') axes.set_ylabel('yyyyyyyyyyyyy') axes.set_title('title biaoti') plt.show()14.1.圖中圖 (A Plot inside of Another Plot)
import numpy as np import matplotlib.pyplot as plt fig = plt.figure() X = [1, 2, 3, 4, 5, 6, 7] Y = [1, 3, 4, 2, 5, 8, 6] axes1 = fig.add_axes([0.1, 0.1, 0.9, 0.9]) # main axes # add_axes 參數rect The dimensions [left, bottom, width, height] of the new axes. # All quantities are in fractions of figure width and height. axes2 = fig.add_axes([0.2, 0.6, 0.4, 0.3]) # inside axes # main figure axes1.plot(X, Y, 'r') axes1.set_xlabel('x') axes1.set_ylabel('y') axes1.set_title('title') # insert axes2.plot(Y, X, 'g') axes2.set_xlabel('y') axes2.set_ylabel('x') axes2.set_title('title inside') plt.show()14.2.設定繪圖范圍 (Setting the Plot Range)
配置軸的范圍可以通過在軸對象中使用set_ylim和set_xlim方法來完成。 使用axis(‘tight’),可以自動創建"tightly fitted" 的軸范圍:
import numpy as np import matplotlib.pyplot as plt fig, axes = plt.subplots(1, 3, figsize=(10, 4)) x = np.arange(0, 5, 0.25) axes[0].plot(x, x**2, x, x**3) axes[0].set_title("default axes ranges") axes[1].plot(x, x**2, x, x**3) axes[1].axis('tight') axes[1].set_title("tight axes") axes[2].plot(x, x**2, x, x**3) axes[2].set_ylim([0, 60]) axes[2].set_xlim([2, 5]) axes[2].set_title("custom axes range") plt.show()14.3.對數尺度(Logarithmic Scale)
可以為一個或兩個軸設置對數尺度。使用接受一個參數(值為log)的set_xscale和set_yscale方法分別設置每個軸的scale:
總結
以上是生活随笔為你收集整理的14_面向对象API绘图、图中图 (A Plot inside of Another Plot)、设定绘图范围Setting the Plot Range、对数尺度Logarithmic Scale的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 双鸭山驾车到伊犁哈萨克自治州科桑溶洞国家
- 下一篇: 15_多子图-Subplot、Subpl