可以在绘图时将一个数值在色标中设为透明吗?

huangapple go评论86阅读模式
英文:

Can you make a value transparent in a colorbar when plotting?

问题

有没有办法在使用matplotlib colormaps绘图时将特定颜色设置为透明?我有一个差异图,其中包含正值和负值,我希望'零'天的部分变为透明。纯白色不适用,因为底图下面有一个我希望在零变化区域显示的基础地图。

'turbo' 颜色映射非常适合 - 如果有办法编辑数值使零变为透明。

h = data.plot('Days_Difference', time=-1, ax=ax, colorbar=False, clim=(-10, 10), cmap='turbo')
英文:

does anyone know of a way to make a certain color transparent when plotting using matplotlib colormaps? I have a difference plot with positive and negative values, and would like the 'zero' days where nothing has changed to be transparent. A solid white won't work because I have a base map underneath that I would like showing in the areas of zero change.

The 'turbo' color map is perfect - if there is a way I can edit the values to make zero transparent.

h=data.plot('Days_Difference', time=-1, ax=ax, colorbar=False, clim=(-10, 10), cmap='turbo')

答案1

得分: 1

使用您的色标的set_bad方法将屏蔽值设置为透明(alpha=0)

masked_data = numpy.ma.masked_equal(data, 0) # 屏蔽值为0的数据

# 基于'turbo'色标创建自定义色标
cmap = matplotlib.colormaps["turbo"]
cmap.set_bad(alpha=0)  # 使屏蔽值透明

h=masked_data.plot('Days_Difference', time=-1, ax=ax, colorbar=False, clim=(-10, 10), cmap=cmap)
英文:

Use the set_bad method of your colormap to set the masked values to transparent(alpha=0)

masked_data = numpy.ma.masked_equal(data, 0) # Mask values at 0

# Create a custom colormap based on 'turbo' colormap
cmap = matplotlib.colormaps["turbo"]
cmap.set_bad(alpha=0)  # Make masked values transparent

h=masked_data.plot('Days_Difference', time=-1, ax=ax, colorbar=False, clim=(-10, 10), cmap=cmap)

huangapple
  • 本文由 发表于 2023年6月19日 14:34:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76504149.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定