python - 如何在 imshow() 的颜色条上添加一条线

标签 python matplotlib colorbar

基本上,我找到了these有关如何在颜色条上添加自定义线或点的说明,但我的代码没有任何反应。

我尝试更改 zorder,或切换到 pyplot 样式,但仍然无法使其工作。

fig, ax = plt.subplots()
im = ax.imshow(data, cmap='rainbow')

cbar = ax.figure.colorbar(im)
cbar.outline.set_visible(False)
cbar.ax.set_ylabel("α", rotation=0, va="bottom")
# None of them does anything
cbar.ax.plot(0.5, 0.5, 'k.', label="Ref")
cbar.ax.plot(0.5, 3, 'k.', label="Ref")
cbar.ax.plot([0, 1], [3, 3], 'k', label="Ref")

到目前为止的数字看起来像 this

我正在使用 matplotlib 3.1.1

最佳答案

Matplotlib 会将颜色条的 x 和 y 限制设置为相同的值。因此,如果颜色条的 y 限制为 1.8 和 7.2,则 x 限制也是如此。您需要在这些限制内绘图才能看到标记。

使用 axhline 可能比使用 plot 绘制线条更简单。要标记此标记值,您可以将其添加到颜色条刻度和刻度标签中。

# clim = cbar.ax.get_ylim()          # find axis limits
# cbar.ax.plot(mean(clim), 3, 'k.')  # point at 3 in the middle of x axis
cbar.ax.axhline(y=3, c='w')          # line at 3

# Set label
original_ticks = list(cbar.get_ticks())
cbar.set_ticks(original_ticks + [3])
cbar.set_ticklabels(original_ticks + ['Ref'])

enter image description here

关于python - 如何在 imshow() 的颜色条上添加一条线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57532474/

相关文章:

python - 如何找出特定模块花费的总时间?

python - 使用os.system调用PowerShell时出错

python - “int”对象没有属性 'x'

python - 如何在 Pairplot 中使用科学计数法

Python matplotlib : How to tick and ticklabel an axis/object independently of the object's scale

python - 如何将色阶标签移动到 matplotlib/xarray 中彩色字段的中间?

python - 使用 Pandas,如何对两列使用 if/then 逻辑来填充另一列?

python - 从 NumPy、matplotlib 包导入 python 子模块有什么区别

python - 简单的图形不代表数据

python - 如何为迭代添加的补丁添加颜色条?