user2398029
user2398029

Reputation: 6947

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 image

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

Upvotes: 2

Views: 667

Answers (1)

Joe Kington
Joe Kington

Reputation: 284840

You need to use the extent keyword argument instead of position. However, you'll need to specify a maximum as well as a start (i.e. 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()

enter image description here

Upvotes: 4

Related Questions