Matplotlib如何在尺寸极小的柱状图柱体内部添加可阅读文本注释
Matplotlib极小柱体内置文本注释实现方案
问题描述
使用Matplotlib绘制柱状图时,数值极小的柱体无法放入可阅读尺寸的文本,要么字号过小难以辨识,要么文本溢出柱体范围。
最小复现代码
import matplotlib.pyplot as plt import numpy as np vals = [0.09, 0.08, 0.05, 0.03, 0.03, 0.02, 0.01] titles = ['cat1', 'cat2', 'cat3', 'cat4', 'cat5', 'cat6', 'cat7'] color_list = ['#FF9349'] * len(vals) # general vals base = 2.43 width = 0.05 fig_w = 4 fig_h = 4 lower = [] upper = [] # calculate lower and upper ranges for i in range(len(vals)): lower.append(base) upper.append(base - vals[i]) base -= vals[i] x = np.arange(0, width*len(upper), width) height = [upper[i] - lower[i] for i in range(len(upper))] x_axis_labs = [' {} {}'.format(perc, val) for perc, val in zip(vals, titles)] # init figure plt.figure(figsize=(fig_w, fig_h)) plt.bar(x=x, height=height, bottom=lower, color=color_list, width=width) # no borders plt.box(False) plt.tick_params(left=False, right=False, labelleft=False, labelbottom=False, bottom=False) # annotations for i in range(len(x_axis_labs)): plt.text( x=x[i], y=lower[i]-0.01, # subtract a little more s=x_axis_labs[i], size=10, rotation=270, verticalalignment='center_baseline', ) plt.tight_layout() plt.margins(x=0) plt.margins(y=0) plt.show()
原运行效果:

文本溢出柱体效果:
可行解决方案
方案1:放大垂直方向画布比例
最简单的适配方式,直接加大画布高度放大极小柱体的物理显示尺寸,无需修改核心逻辑:
- 将
fig_h从4调整为1215,垂直方向放大34倍后,0.01高度的柱体物理尺寸足够放下10号大小的竖排文本 - 调整文本位置到柱体垂直居中位置
修改后核心代码:
# 修改画布高度 fig_w = 4 fig_h = 12 # ... 其余代码不变 ... # 调整注释位置到柱体内部居中 for i in range(len(x_axis_labs)): plt.text( x=x[i], y=lower[i] + height[i]/2, s=x_axis_labs[i], size=10, rotation=270, horizontalalignment='center', verticalalignment='center', )
方案2:阈值判断+引线注释
如果不能修改整体画布比例,可以给柱高设置阈值,极小柱体用外置引线标注,保证文本可读性:
threshold = 0.03 # 小于该高度的柱体使用外置注释 for i in range(len(x_axis_labs)): if abs(height[i]) >= threshold: # 尺寸足够的柱体内置文本 plt.text( x=x[i], y=lower[i] + height[i]/2, s=x_axis_labs[i], size=9, rotation=270, ha='center', va='center' ) else: # 极小柱体用引线指向,文本外置 plt.annotate( x_axis_labs[i], xy=(x[i], lower[i] + height[i]/2), xytext=(x[i] + 0.04, lower[i] + height[i]/2), size=9, rotation=270, ha='left', va='center', arrowprops=dict(arrowstyle='->', color='#666', lw=0.7) )
方案3:Y轴对数缩放
如果柱体高度差异量级极大,可开启Y轴对数尺度,自动放大小数值区域的显示比例,适合专业分析场景:
在初始化画布后添加一行代码即可:
plt.yscale('log')
内容的提问来源于stack exchange,提问作者John Stud
相关产品推荐
相关产品推荐

