簡體   English   中英

Pyplot contourf 不填寫“0”級別

[英]Pyplot contourf don't fill in "0" level

我正在繪制來自天氣模型輸出的降水數據。 我正在使用 contourf 對我擁有的數據進行輪廓分析。 但是,我不希望它用顏色填充“0”級別(只有值>0)。 有沒有好的方法來做到這一點? 我試過弄亂關卡。

這是我用來繪制的代碼:

m = Basemap(projection='stere', lon_0=centlon, lat_0=centlat,
            lat_ts=centlat, width=width, height=height)

m.drawcoastlines()
m.drawstates()
m.drawcountries()
parallels = np.arange(0., 90, 10.)
m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10)
meridians = np.arange(180., 360, 10.)
m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10)

lons, lats = m.makegrid(nx, ny)
x, y = m(lons, lats)
cs = m.contourf(x, y, snowfall)
cbar = plt.colorbar(cs)
cbar.ax.set_ylabel("Accumulated Snow (km/m^2)")
plt.show()

這是我得到的圖像。

降水圖

降雪數據集示例如下所示:

0 0 0 0 0 0
0 0 1 1 1 0 
0 1 2 2 1 0
0 2 3 2 1 0
0 1 0 1 2 0 
0 0 0 0 0 0

我能夠自己弄清楚事情,找到解決此問題的兩種方法。

  1. 使用以下命令屏蔽掉數據集中所有<0.01的數據

     np.ma.masked_less(snowfall, 0.01) 

    要么

  2. 將圖的級別設置為0.01->最大值

     levels = np.linspace(0.1, 10, 100) 

    然后

     cs = m.contourf(x, y, snowfall, levels) 

我發現選項1最適合我。

如果您未在levels包含0 ,則不會在0等級上繪制輪廓。

例如:

import numpy as np
import matplotlib.pyplot as plt

a = np.array([
        [0, 0, 0, 0, 0, 0],
        [0, 0, 1, 1, 1, 0],
        [0, 1, 2, 2, 1, 0],
        [0, 2, 3, 2, 1, 0],
        [0, 1, 0, 1, 2, 0],
        [0, 0, 0, 0, 0, 0]
        ])

fig, ax = plt.subplots(1)

p = ax.contourf(a, levels=np.linspace(0.5, 3.0, 11))
fig.colorbar(p)

plt.show()

產量:

在此處輸入圖片說明

另一種方法是屏蔽任何為0的數據點:

p = ax.contourf(np.ma.masked_array(a, mask=(a==0)),
        levels=np.linspace(0.0, 3.0, 13))
fig.colorbar(p)

看起來像:

在此處輸入圖片說明

我認為由您決定最匹配哪個情節。

這也可以使用來自ticker子類的'locator'和MaxNLocator('prune ='lower')來實現。 請參閱文檔

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker


a = np.array([
    [0, 0, 0, 0, 0, 0],
    [0, 0, 1, 1, 1, 0],
    [0, 1, 2, 2, 1, 0],
    [0, 2, 3, 2, 1, 0],
    [0, 1, 0, 1, 2, 0],
    [0, 0, 0, 0, 0, 0]
    ])

fig, ax = plt.subplots(1)

p = ax.contourf(a, locator = ticker.MaxNLocator(prune = 'lower'))
fig.colorbar(p)

plt.show()

輸出圖像

'nbins' 參數可用於控制間隔(級別)的數量

p = ax.contourf(a, locator = ticker.MaxNLocator(prune = 'lower'), nbins = 5)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM