繁体   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