简体   繁体   中英

Setting position of contour sub-plot in Matplotlib

I am working on identifying tumors in CT images, using SciPy. Once I've identified the slice containing the tumor, I retrieve the slice using:

slice_x, slice_y = ndimage.find_objects(label_im==label)[0]

I then plot the full image as follows:

plt.imshow(image, cmap='gray')

I want to overlay the contour of the extracted slice (containing the tumor) on top of the original image in the appropriate location. However, I can't get the contour plot to lie on top of the proper region. Instead, the contour plot always lies in the top-left corner of the image. Here's what I'm using:

plt.contour(mask[slice_x, slice_y], position=(slice_x.start, \
slice_y.start), linewidths=2, colors='r')

Here is the result:

CT图像

How can I set the position of the contour plot inside the main plot? Thanks!

You need to use the extent keyword argument instead of position . However, you'll need to specify a maximum as well as a start (ie it needs to be extent=[xmin, xmax, ymin, ymax] )

In your case, it would look something like:

extent=[xslice.start, xslice.stop+1, yslice.start, yslice.stop+1]
plt.contour(mask[xslice, yslice], extent=extent)

Note that you may need to use the origin keyword argument (or flip ymin and ymax) to control the way the input data is interpreted.

Alternately, you could do something like the following:

x, y = np.mgrid[xslice, yslice]
plt.contour(x, y, mask[xslcie, yslice])

It will be a bit inefficient if you're working with a large region, but it's much cleaner.

As a full example of the latter approach:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm

data = np.random.random((100,100))

xslice, yslice = slice(20, 30), slice(45, 65)

plt.imshow(data, cmap=cm.gray)

x, y = np.mgrid[xslice, yslice]
plt.contour(x, y, data[xslice, yslice])

plt.show()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM