2014-11-23 165 views
2

下面的代码产生的圆形图案:Matplotlib“灰色”颜色表不跨越全黑到白范围

import numpy as np 
import matplotlib.pyplot as mp 

def sphere_depth(x, y, depth, radius): 
    squ = x**2 + y**2 
    rsqu = radius**2 
    squ[squ > rsqu] = rsqu 
    res = np.sqrt(rsqu - squ) 
    res -= (radius - depth) 
    res[res < 0.] = 0. 
    return res 

y_pix = x_pix = 100. 

c_steps = 10 

x, y = np.mgrid[0:x_pix:1, 0:y_pix:1] 
z = sphere_depth(x - x_pix/2, y - y_pix/2, 5., 100.) 
lvls = np.linspace(z.min(), z.max(), c_steps) 

mp.close(1) 
fig = mp.figure(1) 
mp.axes([0, 0, 1, 1], frameon=False) 
mp.contourf(x, y, z, cmap=mp.cm.gray, levels=lvls) 
mp.axis('off') 
mp.savefig("test.png") 

颜色映射设定为“灰色”和我期望的最低值对应于黑色最大值为白色。虽然后者是事实,但前者并不适用于这个例子。最低值为深灰色。这可以在增加c_steps时进行调整,但我需要一个非常粗糙的灰色彩色贴图。感谢任何想法,如何从黑色开始,以白色结束。

+0

将'lvls'改为100.YOu只有10个级别。所以colormap将只显示这10个级别。 – ssm 2014-11-23 13:03:44

+0

这是故意的,正如我在我的问题中解释的那样。 – Clemens 2014-11-23 13:32:27

回答

1

contourf的行为与imshowpcolormesh有点不同。这是故意与contour保持一致,并且由于层次的定义方式。

每个级别范围的颜色由该范围的中点定义。 (另外,您的中心轮廓实际上并不是完全白色的,但它在视觉上与它完全相同。)

要指定您希望第一个间隔填充“纯”黑色,请在示例中设置vmin=mean(lvls[:1])

举个例子,根据你的问题的很好的例子:

import numpy as np 
import matplotlib.pyplot as plt 

def sphere_depth(x, y, depth, radius): 
    squ = x**2 + y**2 
    rsqu = radius**2 
    squ[squ > rsqu] = rsqu 
    res = np.sqrt(rsqu - squ) 
    res -= (radius - depth) 
    res[res < 0.] = 0. 
    return res 

y_pix = x_pix = 100. 

c_steps = 10 

x, y = np.mgrid[0:x_pix:1, 0:y_pix:1] 
z = sphere_depth(x - x_pix/2, y - y_pix/2, 5., 100.) 
lvls = np.linspace(z.min(), z.max(), c_steps) 

fig = plt.figure() 
ax = fig.add_axes([0, 0, 1, 1], frameon=False) 
ax.contourf(x, y, z, levels=lvls, cmap=plt.cm.gray, 
      vmin=np.mean(lvls[:2]), vmax=np.mean(lvls[-2:])) 
ax.axis('off') 

plt.show() 

enter image description here

只是为了对比,这里是从原来的例子形象:

enter image description here

这很微妙,但第一个在边缘有“纯”黑色,第二个没有。

+0

嗨,乔,非常感谢。但是,使用您的代码我无法复制您发布的图片。事实上,当比较一个图像与'vmin = np.mean(lvls [:1]),vmax = np.mean(lvls [-2:])'并且没有该行时,图像** without **具有稍深的背景。 – Clemens 2014-11-25 11:18:17

+0

@Clemens - 对不起,我改变了一些东西,没有重新运行代码,错过了一个错字。'lvls [:1]'是一个错字。它应该是'vmin = np.mean(lvls [:2])'。 – 2014-11-25 16:08:02