【问题标题】:Pyplot contourf don't fill in "0" levelPyplot contourf 不填写“0”级别
【发布时间】:2017-11-27 17:38:17
【问题描述】:

我正在绘制来自天气模型输出的降水数据。我正在使用 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

【问题讨论】:

  • 你能模拟一个类似于snowfall,但可以包含在问题中的数据集吗?
  • 当然,我用该信息编辑了原始帖子。

标签: python matplotlib matplotlib-basemap


【解决方案1】:

这也可以使用来自ticker子类的'locator'和MaxNLocator('prune ='lower')来实现。见docs

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()

Image of output

'nbins'参数可用于控制区间(级别)的数量

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

【讨论】:

    【解决方案2】:

    如果您的 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)
    

    看起来像:

    我想这取决于你,其中哪一个最符合你想要的情节。

    【讨论】:

      【解决方案3】:

      我能够自己解决问题,我发现有两种方法可以解决这个问题。

      1. 使用

        从数据集中屏蔽所有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 最适合我。

      【讨论】:

        猜你喜欢
        • 2018-08-14
        • 1970-01-01
        • 1970-01-01
        • 2021-07-16
        • 1970-01-01
        • 1970-01-01
        • 2019-03-04
        • 2016-07-04
        • 2023-02-19
        相关资源
        最近更新 更多