2014-11-23 74 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

相關問題