谢谢讨论。我可以把答案放在一个函数里,自动调整文本对象的字体大小,根据给定的数据坐标中的宽度和高度(我认为这通常很有用,想在这里分享一下)。
重叠于条形图边缘的文本示例:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.bar(0.5, 0.5, width=0.5)
text = ax.text(0.5, 0.5,
"0.5 (50.00 percent)",
va='top', ha='center',
fontsize=12)
ax.set_xlim(-0.5, 1.5)
相反,自动适应文本对象的字体大小到条形图的宽度:
![在此输入图片描述](https://istack.dev59.com/PZldO.webp)
import matplotlib.pyplot as plt
from matplotlib.transforms import Bbox
def auto_fit_fontsize(text, width, height, fig=None, ax=None):
'''Auto-decrease the fontsize of a text object.
Args:
text (matplotlib.text.Text)
width (float): allowed width in data coordinates
height (float): allowed height in data coordinates
'''
fig = fig or plt.gcf()
ax = ax or plt.gca()
renderer = fig.canvas.get_renderer()
bbox_text = text.get_window_extent(renderer=renderer)
bbox_text = Bbox(ax.transData.inverted().transform(bbox_text))
fits_width = bbox_text.width < width if width else True
fits_height = bbox_text.height < height if height else True
if not all((fits_width, fits_height)):
text.set_fontsize(text.get_fontsize()-1)
auto_fit_fontsize(text, width, height, fig, ax)
fig, ax = plt.subplots()
ax.bar(0.5, 0.5, width=0.5)
text = ax.text(0.5, 0.5,
"0.5 (50.00 percent)",
va='top', ha='center',
fontsize=12)
ax.set_xlim(-0.5, 1.5)
auto_fit_fontsize(text, 0.5, None, fig=fig, ax=ax)
![enter image description here](https://istack.dev59.com/kbijQ.webp)