如何在 Matplotlib 中快速繪製數千個圓圈?


要在 Matplotlib 中快速繪製數千個圓圈,我們將必須使用 matplotlib.collections。在本案例中,我們將使用 CircleCollection

步驟

  • 從 matplotlib 中匯入 collections 包以及 pyplotnumpy
  • 設定圖形大小,並調整子圖之間及周圍的填充。
  • 初始化變數 “num”,用於表示小圓圈的數量,和 “sizes”,用於表示圓圈的大小。
  • 建立一個圓形補丁列表。
  • 在當前軸上新增圓形補丁藝術家。
  • 設定軸的邊距。
  • 要顯示圖形,使用 show() 方法。

示例

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.collections as mc

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

num = 1000
sizes = 50 * np.random.random(num)
xy = 10 * np.random.random((num, 2))

patches = [plt.Circle(center, size) for center, size in zip(xy, sizes)]

fig, ax = plt.subplots()

collection = mc.CircleCollection(sizes, offsets=xy, transOffset=ax.transData, color='green')
ax.add_collection(collection)

ax.margins(0.01)

plt.show()

輸出

將生成以下輸出

更新於:2021 年 9 月 22 日

1K+ 瀏覽

開始你的 職業

請完成課程以獲得認證

開始
廣告
© . All rights reserved.