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

Xarray绘图中手动设置色条刻度标签的不同有效数字

自定义Xarray色条刻度标签的显示格式

问题场景

使用Xarray绘制contourf图时,手动设置色条刻度为[0.001, 0.2, 0.5, 1.0, 1.5, 2.0],但所有标签默认统一显示为三位小数格式(如0.200、1.000),需要让每个刻度显示对应有效数字:[0.001, 0.2, 0.5, 1.0, 1.5, 2.0]。

用户原始代码:

import matplotlib.pyplot as plt
import numpy as np
import cartopy.crs as ccrs
import xarray as xr
# 假设cmaps已定义

figp = plt.figure(figsize=(10., 10.), dpi=300.)
axp = figp.add_subplot(111, projection=ccrs.PlateCarree())

prect_c[tag, :, :].plot.contourf(
    ax=axp,
    transform=ccrs.PlateCarree(),
    cmap=cmaps.cmp_haxby_r,
    levels=np.insert(np.arange(0., 2.1, 0.1), 1, 0.001),
    add_colorbar=True,
    add_labels=False,
    extend='max',
    cbar_kwargs={
        'orientation': 'horizontal',
        'shrink': 0.8,
        'pad': 0.08,
        'label': 'mm/day',
        'ticks': [0.001, 0.2, 0.5, 1.0, 1.5, 2.0],
    },
)

解决方案

要实现自定义刻度标签格式,可通过cbar_kwargs添加formatter参数,直接指定每个刻度对应的显示文本,或动态生成格式。

方法1:直接指定标签文本(最贴合需求)

使用matplotlib.ticker.FixedFormatter,手动定义每个刻度对应的显示字符串,确保与ticks列表一一对应:

import matplotlib.pyplot as plt
import numpy as np
import cartopy.crs as ccrs
from matplotlib.ticker import FixedFormatter

figp = plt.figure(figsize=(10., 10.), dpi=300.)
axp = figp.add_subplot(111, projection=ccrs.PlateCarree())

# 定义刻度和对应标签
ticks = [0.001, 0.2, 0.5, 1.0, 1.5, 2.0]
tick_labels = ["0.001", "0.2", "0.5", "1.0", "1.5", "2.0"]

prect_c[tag, :, :].plot.contourf(
    ax=axp,
    transform=ccrs.PlateCarree(),
    cmap=cmaps.cmp_haxby_r,
    levels=np.insert(np.arange(0., 2.1, 0.1), 1, 0.001),
    add_colorbar=True,
    add_labels=False,
    extend='max',
    cbar_kwargs={
        'orientation': 'horizontal',
        'shrink': 0.8,
        'pad': 0.08,
        'label': 'mm/day',
        'ticks': ticks,
        'formatter': FixedFormatter(tick_labels)  # 添加自定义格式器
    },
)

plt.show()

方法2:动态生成格式(更灵活)

使用FuncFormatter根据刻度值动态调整显示格式,比如对0.001显示三位小数,其他值显示一位小数:

import matplotlib.pyplot as plt
import numpy as np
import cartopy.crs as ccrs
from matplotlib.ticker import FuncFormatter

figp = plt.figure(figsize=(10., 10.), dpi=300.)
axp = figp.add_subplot(111, projection=ccrs.PlateCarree())

# 自定义格式函数
def custom_format(x, pos):
    if x == 0.001:
        return f"{x:.3f}"
    else:
        return f"{x:.1f}"

prect_c[tag, :, :].plot.contourf(
    ax=axp,
    transform=ccrs.PlateCarree(),
    cmap=cmaps.cmp_haxby_r,
    levels=np.insert(np.arange(0., 2.1, 0.1), 1, 0.001),
    add_colorbar=True,
    add_labels=False,
    extend='max',
    cbar_kwargs={
        'orientation': 'horizontal',
        'shrink': 0.8,
        'pad': 0.08,
        'label': 'mm/day',
        'ticks': [0.001, 0.2, 0.5, 1.0, 1.5, 2.0],
        'formatter': FuncFormatter(custom_format)  # 添加自定义格式器
    },
)

plt.show()

内容的提问来源于stack exchange,提问作者Alex Thompson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 15:55:19