You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改旧代码实现Colormap归一化的预期效果?

解决Colormap归一化匹配预期效果的问题

问题描述

我想要归一化Colormap,在StackExchange上找到一份5年前的代码,原本可实现需求,但现在无法完全复现预期效果。以下是当前代码、运行结果图及预期效果图,请问需要修改代码的哪部分才能达成目标?

当前代码

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import TwoSlopeNorm
import geopandas as gpd

# generate data
gdf = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
gdf = gdf[gdf.continent == 'Africa']
gdf['random'] = np.random.gamma(2, 2, len(gdf)) - 2

# normalize color
vmin, vmax, vcenter = gdf.random.min(), gdf.random.max(), 0
norm = TwoSlopeNorm(vmin=vmin, vcenter=vcenter, vmax=vmax)
# create a normalized colorbar
cmap = 'RdBu'
cbar = plt.cm.ScalarMappable(norm=norm, cmap=cmap)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 7))
# with no normalization
gdf.plot(column='random', cmap=cmap, legend=True, ax=ax1)

# with normalization
gdf.plot(column='random', cmap=cmap, norm=norm, legend=False, ax=ax2)
# add colorbar
fig.colorbar(cbar, ax=ax2)

当前效果

当前效果

预期效果

预期效果

修改方案

问题出在手动创建并添加colorbar的方式,新版本的geopandas已经支持直接在plot方法中结合norm参数生成符合预期的归一化colorbar,无需手动创建ScalarMappable。具体修改步骤:

  • 删除手动创建ScalarMappable的代码行:
    cbar = plt.cm.ScalarMappable(norm=norm, cmap=cmap)
    
  • 修改右侧绘图的代码,将legend=False改为legend=True,同时保留norm=norm参数:
    # with normalization
    gdf.plot(column='random', cmap=cmap, norm=norm, legend=True, ax=ax2)
    
  • 删除手动添加colorbar的代码行:
    fig.colorbar(cbar, ax=ax2)
    

修改后的完整代码如下:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import TwoSlopeNorm
import geopandas as gpd

# generate data
gdf = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
gdf = gdf[gdf.continent == 'Africa']
gdf['random'] = np.random.gamma(2, 2, len(gdf)) - 2

# normalize color
vmin, vmax, vcenter = gdf.random.min(), gdf.random.max(), 0
norm = TwoSlopeNorm(vmin=vmin, vcenter=vcenter, vmax=vmax)
cmap = 'RdBu'

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 7))
# with no normalization
gdf.plot(column='random', cmap=cmap, legend=True, ax=ax1)

# with normalization
gdf.plot(column='random', cmap=cmap, norm=norm, legend=True, ax=ax2)

这样修改后,右侧的colorbar会和绘图使用完全一致的归一化规则,颜色映射和刻度显示都会匹配预期效果。

内容的提问来源于stack exchange,提问作者Stücke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 14:45:30