【问题标题】:Generating just a colorbar with labels仅生成带有标签的颜色条
【发布时间】:2023-02-08 18:36:04
【问题描述】:

我正在尝试在 matplotlib 中仅生成一个颜色条,以配合一系列集群图,遵循 this guide

这是我当前的代码:

fig, ax = plt.subplots(figsize=(3,8))
cmap = mpl.cm.inferno
bounds = [0,1,2,3,4,5]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
fig.colorbar(
    mpl.cm.ScalarMappable(cmap=cmap, norm=norm),
    ticks=[0.5,1.5,2.5,3.5,4.5],
    # labels=["A", "B", "C", "D", "E"],
    cax=ax)

但我想为每个刻度添加标签。我该怎么做呢? colorbar() 无法识别任何 label 样式的参数。

此问题与回答herehere 的问题不同:我正在生成只是一个颜色条,所以使用像fig.colorbar.set_ticklabels()这样的方法是行不通的。 我努力了

mycb = fig.colorbar(
    mpl.cm.ScalarMappable(cmap=cmap, norm=norm),
    ticks=[0.5,1.5,2.5,3.5,4.5],
    cax=ax)

## opt 1
mycb.set_ticklabels = ["A", "B", "C", "D", "E"]

## opt2
mycb.ax.set_yticklabels = ["A", "B", "C", "D", "E"]


也不会在我的颜色条的刻度上产生标签。

【问题讨论】:

    标签: python matplotlib colorbar


    【解决方案1】:

    正如 docs for Colorbar class 告诉我们的那样,Colorbar 可以将 Formatter 作为参数之一(即 format)。采用一系列标签的 Formatter 称为 FixedFormatter,因此这段代码就足够了:

    from matplotlib.ticker import FixedFormatter
    mycb = fig.colorbar(
        mpl.cm.ScalarMappable(cmap=cmap, norm=norm),
        ticks=[0.5,1.5,2.5,3.5,4.5],
        format=FixedFormatter(['A', 'B', 'C', 'D', 'E']),
        cax=ax)
    

    结果如下图:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      相关资源
      最近更新 更多