简体   繁体   English

如何创建带有标签的自定义独立 matplotlib 彩条?

[英]How to create custom standalone matplotlib colorbar with labels?

I want to create a custom and standalone matplotlib colorbar with text labels.我想创建一个带有文本标签的自定义和独立 matplotlib 颜色条。 However, I couldn't assign the labels to the colors in colorbar correctly.但是,我无法正确地将标签分配给颜色栏中的 colors。 How can I assign text labels to each color in colorbar with matplotlib?如何使用 matplotlib 为颜色栏中的每种颜色分配文本标签?

import matplotlib.colorbar as colorbar
import matplotlib.colors as clr
import matplotlib.pyplot as plt

cb_colors = ["#000000", "#808000", "#D3D3D3", "#FFFFFF", "#000080", "#FF4500", "#696969", "#FFFFE0"]
cmap_ = clr.ListedColormap(cb_colors)

fig = plt.figure()
ax = fig.add_axes([0.05, 0.80, 0.9, 0.1])

cb = colorbar.ColorbarBase(ax, orientation='horizontal', 
                               cmap=cmap_)

cb.ax.set_xticks([0, 1, 2, 3, 4, 5, 6, 7])
cb.ax.set_xticklabels(["A", "B", "C", "D", 
                       "E", "F", "G", "H"])

在此处输入图像描述

PS: Even I have changed code to the below one it didn't solve my problem. PS:即使我将代码更改为以下代码,它也没有解决我的问题。

cb.set_ticks([0, 1, 2, 3, 4, 5, 6, 7])
cb.set_ticklabels(["A", "B", "C", "D", 
                       "E", "F", "G", "H"])

在此处输入图像描述

The default internal numbering is from 0 to 1. A tick at a position larger than 1 will not be visible.默认内部编号是从 0 到 1。position 大于 1 的刻度将不可见。 The internal numbering can be changed via a norm .内部编号可以通过norm更改。 Letting the values range between -0.5 and 7.5 will have the positions for 0,1,...,7 nicely at the center of each color:让值在 -0.5 和 7.5 之间的范围内将有 0,1,...,7 的位置很好地位于每种颜色的中心:

import matplotlib.colorbar as colorbar
import matplotlib.colors as clr
import matplotlib.pyplot as plt

cb_colors = ["#000000", "#808000", "#D3D3D3", "#FFFFFF", "#000080", "#FF4500", "#696969", "#FFFFE0"]
num_colors = len(cb_colors)
cmap_ = clr.ListedColormap(cb_colors)

fig = plt.figure()
ax = fig.add_axes([0.05, 0.80, 0.9, 0.1])

cb = colorbar.ColorbarBase(ax, orientation='horizontal',
                           cmap=cmap_, norm=plt.Normalize(-0.5, num_colors - 0.5))

cb.set_ticks(range(num_colors))
cb.ax.set_xticklabels(["A", "B", "C", "D", "E", "F", "G", "H"])
plt.show()

颜色中心带有标签的颜色条

If you need to keep the default range 0 to 1, you could use cb.set_ticks(np.linspace(0, 1, 2*num_colors+1)[1::2]) .如果需要保持默认范围 0 到 1,可以使用cb.set_ticks(np.linspace(0, 1, 2*num_colors+1)[1::2]) This divides the range into 17 equally spaced positions and would use the odd ones for the ticks.这将范围划分为 17 个等间距的位置,并将使用奇数的位置作为刻度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM