在 Matplotlib 中繪製兩幅圖之間的線條


要繪製 matplotlib 中兩幅圖之間的線條,我們可以按以下步驟操作:

  • 建立一副新影像或啟用一副現有的影像。

  • 作為子圖佈置的一部分,向影像中加入兩個軸(ax1 和 ax2)。

  • 使用 numpy 建立隨機資料 x 和 y。

  • 在 ax1 和 ax2 兩個軸上繪製 x 和 y 資料點,顏色為紅色,標記為菱形。

  • 初始化兩個變數 i 和 j,以獲取子圖上的不同資料點。

  • 製作 xy 和 mn 元組作為位置,用於在子圖上新增補丁。

  • 新增一個補丁,將兩個點(可能在不同的軸中)con1 和 con2 連線起來。

  • 為 con1 和 con2 新增 artist。

  • 在 ax1 和 ax2 上繪製資料點 (x[i], y[i]) 和 (x[j], y[j]) 之間的直線,以連線這些補丁。

  • 要顯示影像,請使用 show() 方法。

示例

import matplotlib.pyplot as plt
from matplotlib.patches import ConnectionPatch
import numpy as np
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
x, y = np.random.rand(100), np.random.rand(100)
ax1.plot(x, y, 'd', c='r')
ax2.plot(x, y, 'd', c='r')
i = 10
xy = (x[i], y[i])
con1 = ConnectionPatch(xyA=xy, xyB=xy, coordsA="data", coordsB="data", axesA=ax2, axesB=ax1, color="blue")
j = 12
mn = (x[j], y[j])
con2 = ConnectionPatch(xyA=mn, xyB=mn, coordsA="data", coordsB="data", axesA=ax2, axesB=ax1, color="blue")
ax2.add_artist(con1)
ax2.add_artist(con2)
ax1.plot(x[i], y[i], 'bo', markersize=10)
ax2.plot(x[i], y[i], 'bo', markersize=10)
ax1.plot(x[j], y[j], 'bo', markersize=10)
ax2.plot(x[j], y[j], 'bo', markersize=10)
plt.show()

輸出

更新於: 2021 年 5 月 8 日

2K+ 瀏覽次數

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.