如何为pandas hist方法生成的多张子图分别添加x轴、y轴标签
问题解答
该需求完全可以实现,不需要拆分生成多个独立图表。
pandas的DataFrame.hist()方法执行后会返回存储了所有子图Axes对象的二维数组,你只需要遍历这个数组,就可以为每一张子图单独设置x轴、y轴标签等自定义属性。
修改后可直接运行的代码示例
通用场景(统一y轴标签,x轴使用对应字段名)
import matplotlib.pyplot as plt # 接收hist方法返回的子图对象数组 axes = dfConverted[['attack', 'defense', 'link_number', 'pendulum_left', 'pendulum_right', 'stars']].hist(bins=50, figsize=(20,15)) # 遍历所有子图设置标签 for ax_row in axes: for ax in ax_row: # 取子图默认的字段标题作为x轴标签 ax.set_xlabel(ax.get_title()) # 统一设置y轴标签为频数 ax.set_ylabel('频数') # 可选:关闭默认的子图标题,避免和x轴标签重复 # ax.set_title('') # 可选:自动调整布局避免标签重叠 plt.tight_layout() plt.show()
自定义每个子图的专属标签场景
如果你需要给不同字段的子图设置自定义的中文标签,可以用字典做映射匹配:
import matplotlib.pyplot as plt # 定义字段与自定义标签的对应关系 custom_label = { "attack": "怪兽攻击力", "defense": "怪兽防御力", "link_number": "链接怪兽等级", "pendulum_left": "灵摆左刻度值", "pendulum_right": "灵摆右刻度值", "stars": "怪兽星级" } axes = dfConverted[['attack', 'defense', 'link_number', 'pendulum_left', 'pendulum_right', 'stars']].hist(bins=50, figsize=(20,15)) for ax_row in axes: for ax in ax_row: col = ax.get_title() if col in custom_label: ax.set_xlabel(custom_label[col]) ax.set_ylabel('样本数量') plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者Majin Venix
相关产品推荐
相关产品推荐

