如何在matplotlib中使用直线轮廓线?

Mat*_*711 3 python matplotlib contour

我正在绘制值imshow,我希望在某个值处有一个轮廓线.但是,pyplot.contour()使用某种插值会导致轮廓线在该点周围成对角线.如何确保线条与我的矩形框完全对齐(所以只有水平线和垂直线)?

(任何想要重现我已经获得的图片的人,这些值都会在这里上传)

数据的图片如下所示: Contourlines

使用此代码生成:

pyplot.imshow(KS_imshow, extent = [5. ,8., 0., 22., ], origin='lower', interpolation='nearest', aspect='auto', cmap = 'Blues', vmin = 0., vmax = 1.)
cbar = pyplot.colorbar()

CS2 = pyplot.contour(ri,phii,KS_imshow,levels=[0.5], colors='r')
cbar.add_lines(CS2)

pyplot.show()
Run Code Online (Sandbox Code Playgroud)

变量ri,phiiKS_imshow在链接文档中.

hit*_*tzg 5

问题在于imshow创建"像素",但基础数据只是点(在中心).因此contour,对所imshow创造的图像一无所知.但是,您可以通过升级原始数据来创建类似的图像,然后使用contour它.它肯定是一个黑客,但它实现了你想要的.边缘仍然存在问题,我不知道如何解决这个问题.

import matplotlib.pyplot as plt
import numpy as np
import scipy.ndimage

# data ranges
xr = [5., 8.]
yr = [0., 22.]

# pixel widths
x_pw = np.diff(xr) / (KS_imshow.shape[1])
y_pw = np.diff(yr) / (KS_imshow.shape[0])

# plot the image
plt.imshow(KS_imshow, extent=xr+yr, origin='lower', interpolation='nearest',
        aspect='auto', cmap='Blues', vmin=0., vmax=1.)
cbar = plt.colorbar()

# upscale by a factor of 50 (might be an issue for large arrays)
highres = scipy.ndimage.zoom(KS_imshow, 50, order=0, mode='nearest') 

# correct the extent by the pixel widths
extent = np.array(xr+yr) + np.array([x_pw, -x_pw, y_pw, -y_pw]).flatten()/2

# create the contours
CS2 = plt.contour(highres, levels=[0.5], extent=extent, origin='lower',
        colors='r', linewidths=2)
cbar.add_lines(CS2)

plt.show()
Run Code Online (Sandbox Code Playgroud)

结果: 在此输入图像描述

但是,为了显示0.5的阈值,我建议自定义色彩图而不是使用轮廓线:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors as mcolors

blues = plt.cm.Blues(np.linspace(0,1,200))
reds = plt.cm.Reds(np.linspace(0,1,200))
colors = np.vstack((blues[0:128,:], reds[-129:,:]))

i = np.linspace(0,1,256)
r = np.column_stack((i, colors[:-1,0], colors[1:,0]))
g = np.column_stack((i, colors[:-1,1], colors[1:,1]))
b = np.column_stack((i, colors[:-1,2], colors[1:,2]))
d = dict(red=r, green=g, blue=b)
mycmap = mcolors.LinearSegmentedColormap('mymap', d, N=256)

plt.imshow(KS_imshow, extent=[5, 8, 0, 22], origin='lower',
        interpolation='nearest', aspect='auto', cmap=mycmap,
        vmin=0., vmax=1.)

cbar = plt.colorbar()

plt.show()
Run Code Online (Sandbox Code Playgroud)

结果: 在此输入图像描述