如何在Axes传入函数后获取其mosaic layout标签?
获取Matplotlib Axes对应的Mosaic布局标签
方法1:利用Axes官方标签属性(推荐)
Matplotlib的Axes对象自带label属性(继承自Artist基类),可用于存储自定义标识。创建子图字典后,给每个Axes绑定对应的mosaic标签,后续在函数中直接读取该属性即可。
示例代码:
import matplotlib.pyplot as plt def test_function(ax): # 获取Axes对应的mosaic标签 print(ax.get_label()) mosaic_subplot_layout = {'axes': [['boxplot'], ['histogram'], ['histogram'], ['histogram']]} my_figure = plt.figure() ax_dict = my_figure.subplot_mosaic(mosaic_subplot_layout['axes']) # 遍历字典,给每个Axes绑定标签 for label, ax in ax_dict.items(): ax.set_label(label) test_function(ax=ax)
运行输出:
boxplot histogram
方法2:给Axes添加自定义属性
如果担心官方label属性与其他场景冲突,可以给Axes对象添加一个专属的自定义属性来存储mosaic标签。
示例代码:
import matplotlib.pyplot as plt def test_function(ax): # 获取自定义的mosaic标签属性 print(ax.mosaic_label) mosaic_subplot_layout = {'axes': [['boxplot'], ['histogram'], ['histogram'], ['histogram']]} my_figure = plt.figure() ax_dict = my_figure.subplot_mosaic(mosaic_subplot_layout['axes']) # 给每个Axes添加自定义属性存储标签 for label, ax in ax_dict.items(): ax.mosaic_label = label test_function(ax=ax)
运行输出与方法1一致。
说明
Matplotlib默认不会自动关联mosaic布局标签与Axes对象,因此必须手动完成绑定。以上两种方法均无需修改函数参数列表,保持了函数仅依赖Axes对象的设计,避免了传入字典键带来的耦合问题。
内容的提问来源于stack exchange,提问作者Python_Learner
相关产品推荐
相关产品推荐

