如何防止Matplotlib注释超出图框范围

2024-10-01 15:48:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着在rotation=90中用它的y轴值(yy)来标记我的条,但是一些低值超出了框架我的xx是从0到5的x轴值。你知道吗

ax_actsumbar.annotate('{:.2e}'.format(yy), xy=(xx+0.5, yy), xycoords='data', \
                      rotation=90)

enter image description here

如何限制框架中的注释?所以每个条的注释都在条的旁边,而不是在框架上。我找到.get_window_extent并尝试应用它,但还没有成功。你知道吗

_actsumbar = ax_actsumbar.annotate('{:.2e}'.format(yy), xy=(xx+0.5, yy), xycoords='data', \
                                   rotation=90)
_actsumbar = ax_actsumbar.annotate('{:.2e}'.format(yy), xy=(xx+0.5, yy), \
                                   xycoords=_actsumbar.get_window_extent, rotation=90)

Tags: 框架formatdatagetaxwindowextentxy
1条回答
网友
1楼 · 发布于 2024-10-01 15:48:55

您可以根据每个栏的高度调整位置:

import matplotlib.pyplot as plt        

x = [0, 1, 2, 3, 4, 5]
y = [2.09e+12, 3.2e+09, 6.41e+10, 6.34e+11, 1.75e+07, 3.29e+09]
colors = ['blue', 'orange', 'green', 'red', 'blue', 'black']

split_point = max(y) / 4.0
bars = plt.bar(x, y, color=colors)

for bar, color in zip(bars, colors):
    bbox = bar.get_bbox()
    va, y = ('top', bbox.y1) if bbox.y1 > split_point else ('bottom', 0)
    plt.annotate(' {:.2e}'.format(bbox.y1), xy=(bbox.x1+0.05, y), xycoords='data', rotation=90, va=va, color=color)

plt.show()

这将计算最高的条,并将任何小于1/4高度的条与底部对齐。你知道吗

matplotlib showing adaptive aligment

相关问题 更多 >

    热门问题