Python 如何更改 matplotlib 颜色条标签的字体属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23172282/
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
How to change font properties of a matplotlib colorbar label?
提问by thengineer
In matplotlib, I want to change the font properties for a colorbarlabel. For example I want the label to appear bold.
在 matplotlib 中,我想更改colorbar标签的字体属性。例如,我希望标签显示为粗体。
Here is some example code:
下面是一些示例代码:
from matplotlib.pylab import *
pcolor(arange(20).reshape(4,5))
cb = colorbar(label='a label')
and the result, where I want "a label"to appear bold:
结果,我希望“标签”显示为粗体:


All other answers on this site only answer how to change ticklabelsor change all fonts in general (via modification of the matplotlibrcfile)
本网站上的所有其他答案仅回答一般如何更改ticklabels或更改所有字体(通过修改matplotlibrc文件)
采纳答案by francesco
This two-liner can be used with any Text property (http://matplotlib.org/api/text_api.html#matplotlib.text.Text)
这个两行可以与任何 Text 属性一起使用(http://matplotlib.org/api/text_api.html#matplotlib.text.Text)
cb = plt.colorbar()
cb.set_label(label='a label',weight='bold')
回答by unutbu
Perhaps use TeX: r'\textbf{a label}'
也许使用 TeX: r'\textbf{a label}'
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rc('text', usetex=True)
plt.pcolor(np.arange(20).reshape(4,5))
cb = plt.colorbar(label=r'\textbf{a label}')
plt.show()


回答by Molly
As an alternative to unutbu's answer you could take advantage of the fact that a color bar is another axes instance in the figure and set the label font like you would set any y-label.
作为 unutbu 答案的替代方案,您可以利用颜色条是图中的另一个轴实例这一事实,并像设置任何 y 标签一样设置标签字体。
from matplotlib.pylab import *
from numpy import arange
pcolor(arange(20).reshape(4,5))
cb = colorbar(label='a label')
ax = cb.ax
text = ax.yaxis.label
font = matplotlib.font_manager.FontProperties(family='times new roman', style='italic', size=16)
text.set_font_properties(font)
show()


回答by Q-man
I agree with francesco, but even shorten to one line:
我同意弗朗西斯科,但甚至缩短为一行:
plt.colorbar().set_label(label='a label',size=15,weight='bold')

