Python matplotlib 颜色条的顶部标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33737427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:52:04  来源:igfitidea点击:

Top label for matplotlib colorbars

pythonmatplotlibcolorbar

提问by Vlas Sokolov

By default matplotlibwould position colorbar labels alongside the vertical colorbars. What is the best way to force the label to be on top of a colorbar? Currently my solution needs adjusting labelpadand yvalues depending on size of the label:

默认情况下,matplotlib将颜色条标签放置在垂直颜色条旁边。强制标签位于颜色条顶部的最佳方法是什么?目前我的解决方案需要根据标签的大小调整labelpady值:

import numpy as np
import matplotlib.pylab as plt 

dat = np.random.randn(10,10)
plt.imshow(dat, interpolation='none')

clb = plt.colorbar()
clb.set_label('label', labelpad=-40, y=1.05, rotation=0)

plt.show()

colorbar top label

颜色条顶部标签

Is there a better, more generic way to do this?

有没有更好,更通用的方法来做到这一点?

采纳答案by tmdavison

You could set the titleof the colorbar axis (which appears above the axis), rather than the label(which appears along the long axis). To access the colorbar's Axes, you can use clb.ax. You can then use set_title, in the same way you can for any other Axesinstance.

您可以设置title颜色条轴的 的(出现在轴上方),而不是label(出现在长轴上)。要访问颜色栏的Axes,您可以使用clb.ax. 然后set_title,您可以像使用任何其他Axes实例一样使用 。

For example:

例如:

import numpy as np
import matplotlib.pylab as plt 

dat = np.random.randn(10,10)
plt.imshow(dat, interpolation='none')

clb = plt.colorbar()
clb.ax.set_title('This is a title')

plt.show()

enter image description here

在此处输入图片说明