【问题标题】:How to prevent Matplotlib annotation out of the frame of the plot如何防止 Matplotlib 注释超出绘图框架
【发布时间】:2018-03-07 13:48:58
【问题描述】:

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

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

如何限制框内的注解?因此,每个条的注释都在条旁边,但不会越过框架。我找到了.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)

【问题讨论】:

  • 我猜你忘了告诉你的要求。例如。为了将注释保留在轴内,只需将它们的下角放在数据坐标中的 0 处即可。但这就是你所追求的吗?没人知道。
  • @ImportanceOfBeingErnest 我更新了这个问题。是的,你能指导一下如何设置数据坐标的角吗?我正在查看文档,数据坐标的参数似乎是“图形点”或“轴点”之类的东西。这是你提到的吗?
  • 我的意思是你需要说出你想要达到的目标。标签应该在哪里?为了让它们进入绘图,只需将 y 坐标设置为零,xy=(xx+0.5, 0), va="bottom"

标签: python python-2.7 matplotlib annotations


【解决方案1】:

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

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 高度的任何东西对齐到底部。

【讨论】:

  • 你能解释一下bbox.y1吗? y1 这里是什么?
  • bbox 是一个矩形,所以你得到左下角和右上角的坐标。他们将它们命名为 x0, y0x1, y1
猜你喜欢
  • 1970-01-01
  • 2017-09-11
  • 2018-01-17
  • 1970-01-01
  • 2017-08-26
  • 2023-03-29
  • 1970-01-01
  • 2012-04-12
  • 1970-01-01
相关资源
最近更新 更多