天天看點

matplotlib之pyplot子產品——填充多邊形(fill)

概述

fill

函數的功能是根據結點之間連線的封閉區域繪制多邊形。

fill

函數的簽名為:

matplotlib.pyplot.fill(*args, data=None, **kwargs)

參數說明如下:

  • *args

    :根據x,y位置确定結點繪制多邊形,可添加一個可選的顔色标記。資料結構為

    x, y, [color]

    序列,支援多組

    x, y, [color]

    序列。必備參數。

    *args

    的應用方式如下:
    plt.fill(x, y)                   
    plt.fill(x, y, "b")               
    plt.fill(x, y, x2, y2)           
    plt.fill(x, y, "b", x2, y2, "r") 
               
  • data

    :帶标簽的資料對象。可索引對象。可選參數。

    例如:

    plt.fill("time", "signal", data={"time": [0, 1, 2], "signal": [0, 1, 0]})

  • **kwargs

    matplotlib.patches.Polygon

    對象的相關屬性。

fill

函數的傳回值為

matplotlib.patches.Polygon

對象清單。

案例1

注意!多邊形是根據資料的順序依次繪制的,是以,相同的結點由于順序不同可能填充出來的多邊形效果也不同。

例如:同樣的資料,第一個子圖繪制了封閉五邊形,第二個子圖未繪制封閉的五邊形,注意結點的次序。

如果想繪制封閉的多邊形需要逆時針依次繪制(坐标點位置)。

matplotlib之pyplot子產品——填充多邊形(fill)
import numpy as np
import matplotlib.pyplot as plt

a = [5, 10, 15, 10, 5]
b = [5, 5, 10, 15, 10]

c = [5, 5, 10, 15, 10]
d = [5, 10, 5, 10, 15]

e = [1, 2, 2, 1]
f = [3, 3, 4, 4]

plt.subplot(221)
plt.plot(a, b, 'o')
plt.fill(a, b, 'r')
for index, item in enumerate(zip(a, b), 1):
    plt.text(item[0], item[1], index)

plt.subplot(222)
plt.plot(c, d, 'o')
plt.fill(c, d, alpha=0.5)
for index, item in enumerate(zip(c, d), 1):
    plt.text(item[0], item[1], index)

plt.subplot(223)
plt.fill(e, f)

plt.subplot(224)
plt.fill("time", "signal",
         data={"time": [2, 4, 4], "signal": [3, 4, 3]})

plt.show()
           

案例2

matplotlib之pyplot子產品——填充多邊形(fill)
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 5 * np.pi, 1000)

y1 = np.sin(x)
y2 = np.sin(2 * x)

plt.fill(x, y1, color="g", alpha=0.3)
plt.fill(x, y2, color="b", alpha=0.3)

plt.show()
           

繼續閱讀