AnnotationBbox与errorbar同绘时不显示的原因及解决咨询
Matplotlib errorbar绘图时AnnotationBbox文本框不显示的问题
我用以下Python代码实现带误差棒的Matplotlib绘图,并在图旁添加AnnotationBbox文本框:
import numpy as np import matplotlib.pyplot as plt from matplotlib.offsetbox import AnnotationBbox, TextArea fig, ax = plt.subplots(layout="constrained") f = np.array([2.15, 2.22, 2.3, 2.43, 2.54, 2.7, 2.79, 2.91, 3.04, 3.2, 3.29]) f_err = 0.01 d = np.array( [ 0.3393, 0.3458, 0.3622666666666667, 0.38306666666666667, 0.4004, 0.429, 0.43939999999999996, 0.45239999999999997, 0.481, 0.5044, 0.5174, ] ) d_err = 0.0052 ax.errorbar(f, d, xerr=f_err, yerr=d_err, fmt=".", label="Measurements") text_area = TextArea("Hello there!!!!!!") text_box = AnnotationBbox( text_area, (1, 1), box_alignment=(0, 1), boxcoords="axes fraction" ) ax.add_artist(text_box) ax.legend() plt.show()
此前代码运行正常,但现在运行时文本框的空间被预留(修改文本长度会改变该空间),但文本内容本身不显示;注释掉ax.errorbar相关代码后,文本框可正常显示。
问题原因
这是constrained_layout布局模式与AnnotationBbox的交互异常导致的:当使用layout="constrained"时,errorbar元素会触发布局的重新计算,使得TextArea的文本渲染被抑制,仅保留了布局预留空间但不显示实际内容。
解决方法
方法一:更换布局模式
将constrained_layout替换为tight_layout,修改初始化代码并在绘图最后手动调用布局调整:
import numpy as np import matplotlib.pyplot as plt from matplotlib.offsetbox import AnnotationBbox, TextArea fig, ax = plt.subplots() # 移除layout="constrained" f = np.array([2.15, 2.22, 2.3, 2.43, 2.54, 2.7, 2.79, 2.91, 3.04, 3.2, 3.29]) f_err = 0.01 d = np.array( [ 0.3393, 0.3458, 0.3622666666666667, 0.38306666666666667, 0.4004, 0.429, 0.43939999999999996, 0.45239999999999997, 0.481, 0.5044, 0.5174, ] ) d_err = 0.0052 ax.errorbar(f, d, xerr=f_err, yerr=d_err, fmt=".", label="Measurements") text_area = TextArea("Hello there!!!!!!") text_box = AnnotationBbox( text_area, (1, 1), box_alignment=(0, 1), boxcoords="axes fraction" ) ax.add_artist(text_box) ax.legend() plt.tight_layout() # 添加手动布局调整 plt.show()
方法二:保留constrained_layout并调整AnnotationBbox参数
添加annotation_clip=False避免文本被裁剪,同时显式设置文本框背景(防止与画布背景融合):
import numpy as np import matplotlib.pyplot as plt from matplotlib.offsetbox import AnnotationBbox, TextArea fig, ax = plt.subplots(layout="constrained") f = np.array([2.15, 2.22, 2.3, 2.43, 2.54, 2.7, 2.79, 2.91, 3.04, 3.2, 3.29]) f_err = 0.01 d = np.array( [ 0.3393, 0.3458, 0.3622666666666667, 0.38306666666666667, 0.4004, 0.429, 0.43939999999999996, 0.45239999999999997, 0.481, 0.5044, 0.5174, ] ) d_err = 0.0052 ax.errorbar(f, d, xerr=f_err, yerr=d_err, fmt=".", label="Measurements") text_area = TextArea("Hello there!!!!!!") text_box = AnnotationBbox( text_area, (1, 1), box_alignment=(0, 1), boxcoords="axes fraction", annotation_clip=False, # 禁止裁剪注释 bboxprops={"facecolor": "white", "edgecolor": "black"} # 设置文本框背景和边框 ) ax.add_artist(text_box) ax.legend() plt.show()
内容的提问来源于stack exchange,提问作者Shai Avr
相关产品推荐
相关产品推荐

