使用 matplotlib.pcolormesh() 将颜色设置为透明的正确方法? [英] Correct way to set color to transparent with matplotlib.pcolormesh()?

查看:156
本文介绍了使用 matplotlib.pcolormesh() 将颜色设置为透明的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用 matplotlib.pcolormesh() 将某个级别(在本例中为 0)下的值绘制为透明,但我似乎无法得到任何东西使用我找到的选项.

I would like values under a certain level (in this case 0) to be plotted as transparent with matplotlib.pcolormesh(), and I cannot seem to get anything working with the options that I have found.

我尝试设置 kwarg vmin=1,并且尝试使用 plt.cm.cmap.set_under(alpha=0) 设置限制.

I have tried setting the kwarg vmin=1, and I have tried setting the limit with plt.cm.cmap.set_under(alpha=0).

更新:在使用示例脚本之后,vmin 似乎对我来说工作正常,所以它似乎与其他一些混淆因素有关.我正在使用 Basemap 并尝试绘制密度图,根据数据的最小值/最大值设置级别(其他所有内容为零).

Update: After playing around with a sample script, it appears that vmin is working correctly for me there, so it appears to be do to some other confounding factor. I am using Basemap and attempting to plot a density map, setting the levels based on the min/max values of the data (with everything else being zero).

我的示例脚本显示了vmin正常运行:

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

x = np.linspace(1,4,num=4)
y = np.linspace(1,6,num=6)
x_mesh, y_mesh = np.meshgrid(x,y)

ydim, xdim = x_mesh.shape

z = np.zeros(((ydim-1),(xdim-1)))

for j in range(ydim-1):
    for i in range(xdim-1):
        z[j,i] = (random.random())+4.

z[1:4,1:2]=0

cmap = plt.cm.Reds
plt.pcolormesh(x,y,z, cmap=cmap, vmin=4)

plt.show()

输出:

推荐答案

您可以使用掩码数组:

import matplotlib.pyplot as plt
import numpy as np

z = np.sin(np.arange(100) / 2).reshape(10, 10)
z = np.ma.masked_array(z, z < -.5)

cmap = plt.cm.Reds
plt.pcolormesh(z, vmin=-1, vmax=1, cmap="RdYlBu")
plt.colorbar()

这篇关于使用 matplotlib.pcolormesh() 将颜色设置为透明的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆