如何在matplotlib的annotate标注文本中对单个词设置加粗效果
解决方案
matplotlib的annotate方法默认对整段文本应用统一样式,终端用的ASCII转义符无法被matplotlib的渲染逻辑识别,因此无法直接用转义符实现局部加粗。可以通过以下两种方法实现需求:
方法一:内置数学文本标记(无额外依赖,写法简单)
直接在需要加粗的词汇外包裹$\mathbf{}$标记即可,matplotlib内置的数学文本渲染器会自动识别并加粗对应内容,无需手动调整坐标。仅需要修改原代码中的文本与annotate调用部分:
# 修改文本内容,用$\mathbf{}$包裹要加粗的词 text = "This is text. I want the word $\mathbf{blah}$ to be Bold." ax_text.axis('off') # 移除原来的weight='bold'参数,仅保留基础配置 ax_text.annotate(text, wrap=True, xy=(-0.12,1), xycoords='axes fraction', verticalalignment='top')
注意:该方法仅适用于英文、数字场景,中文加粗不支持该写法。
方法二:offsetbox文本拼接(兼容性强,支持自定义样式)
如果需要处理中文、或者需要同时设置多种局部样式(不同颜色、字号、斜体等),可以用matplotlib.offsetbox模块的组件拼接不同样式的文本片段,自动完成排版,无需手动计算每个片段的坐标。完整修改后的代码如下:
import pandas as pd import matplotlib.pyplot as plt from matplotlib.offsetbox import TextArea, HPacker, AnchoredOffsetbox fig, (ax, ax_table, ax_text) = plt.subplots(nrows=3, figsize=(10,8), gridspec_kw=dict(height_ratios=[4,1,1])) tbl = (ax_table.table(rowLabels=["RowLabel1","RowLabel2", 'RowLabel3'], colLabels=['ColLabel1', 'ColLabel2', 'ColLabel3'], cellText=[["1", "2", "3"], ["1", "2", "3"], ["1", "2", "3"]], cellLoc='center', loc='center')) tbl.auto_set_font_size(True) tbl.set_fontsize(10) tbl.scale(1,1) ax_table.axis('off') ax_text.axis('off') # 按样式拆分文本为独立片段,分别设置样式 text_part1 = TextArea("This is text. I want the word '", textprops={"fontsize":10}) text_bold = TextArea("blah", textprops={"fontsize":10, "weight":"bold"}) text_part2 = TextArea("' to be Bold.", textprops={"fontsize":10}) # 水平拼接所有文本片段,自动处理间距 text_box = HPacker(children=[text_part1, text_bold, text_part2], align="center", pad=0, sep=2) # 将拼接好的文本整体挂载到ax_text上,仅调整整体位置参数即可 anchored_box = AnchoredOffsetbox(loc="upper left", child=text_box, pad=0, frameon=False, bbox_to_anchor=(-0.12, 1), bbox_transform=ax_text.transAxes, borderpad=0) ax_text.add_artist(anchored_box) plt.show()
内容的提问来源于stack exchange,提问作者narnia649
相关产品推荐
相关产品推荐

