簡體   English   中英

將多個 matplotlib 圖形合並為一個

[英]Combine multiple matplotlib figures into one

我有一個函數,它采用增強的 dicom 文件並執行以下操作:

  1. 使用 for 循環從 dicom 文件創建單個切片,然后將其索引到圍繞一組六個斑點的較小數組中。
  2. 第二個 for 循環在六個斑點周圍繪制圓圈,一個用於背景
  3. 顯示所有繪制的圓圈和當前切片位置的圖像。

當我調用該函數時,我可以創建多個顯示在不同圖形中的圖像。 那么,我怎樣才能將所有這些數字合二為一呢? 理想情況下,我想以 3x3 網格顯示它們。

這是我當前的代碼:

import matplotlib.pyplot as plt
import pydicom # Used for opening DICOM files
import numpy as np # General mathematical package
from pylab import text

# Import DICOM files
filename = "U:/File location" 
ds = pydicom.dcmread(filename)

# Speck Locations
centerSpeck = (1690, 1477)
centerSpeck2 = (100, 100)
twelveOclockSpeck = (45, 84)
twoOkclockSpeck = (66, 148)
tenOclockSpeck = (136, 147)
fiveOclockSpeck = (157, 82)
sevenOclockSpeck = (102, 41)
backgroundSignalValue = (71, 63)

speckLocations = np.array([centerSpeck2, twelveOclockSpeck, twoOkclockSpeck, fiveOclockSpeck, sevenOclockSpeck, tenOclockSpeck, backgroundSignalValue])

# Function that draws a circle around a given pixel
def drawCircle(arrayToPLot, zeroIndex, oneIndex, specks, r = 10):
    x = speckLocations[:,1] # get x axis variables from the speckLocations array
    y = speckLocations[:,0] # get y axis variables from the speckLocations array
    for i in range(zeroIndex,oneIndex,1): # For loop, note that the function range is: range(start, stop, step)
        tempIm = arrayToPLot.pixel_array[i,:,:].astype(float) # Get one slice as float
        slicedArray = tempIm[centerSpeck[0]-100:centerSpeck[0]+100, centerSpeck[1]-100:centerSpeck[1]+100].astype(float)
        for x,y in (speckLocations):
            plt.imshow(slicedArray, cmap='gray')
            circle = plt.Circle((y, x),r, fc='none', ec="red")
            plt.gca().add_patch(circle)    
            text(10, 180, i, fontsize=12, color='red') # Print the current slice on the image

        plt.show() # Plot each slice with circles drawn around all the specks and the background signal value location

#Call the function  
drawCircle(ds, 33, 34, speckLocations)

在下文中,我們將使用plt.subplots方法生成圖形和axes網格,即有人理解為子圖的 Matplotlib 對象......

二維網格上的迭代首先為您提供一行網格,該行上的第二次迭代為您提供單個子圖。 當我們挑選出一個軸時,是時候調用您的函數(您有責任區分要繪制的數據,因為從您的問題中不清楚您想要做什么),但是有一個額外的參數,即當前軸。

fig, ax_grid = plt.subplots(3,3)
for ax_row in ax_grid:
    for ax in ax_row:
        drawCircle(ax, ds, 33, 34, speckLocations)
plt.tight_layout()
plt.show()

最后我們展示圖,調用tight_layout以獲得更好的子圖排列。


當然,我們必須修改圓繪圖函數……首先我們將ax添加到參數列表中,接下來我們修改對plt方法的調用以使用ax對象的方法:

def drawCircle(ax, arrayToPLot, zeroIndex, oneIndex, specks, r = 10):
    ...
    ax.imshow(...)
    ...
    ax.add_patch(circle)
    ax.text(10, 180, i, fontsize=12, color='red')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM