[英]Setting position of contour sub-plot in Matplotlib
I am working on identifying tumors in CT images, using SciPy.我正在使用 SciPy 识别 CT 图像中的肿瘤。 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:结果如下:
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
.您需要使用
extent
关键字参数而不是position
。 However, you'll need to specify a maximum as well as a start (ie it needs to be extent=[xmin, xmax, ymin, ymax]
)但是,您需要指定最大值和起点(即它必须是
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.请注意,您可能需要使用
origin
关键字参数(或翻转 ymin 和 ymax)来控制解释输入数据的方式。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.