代码之家  ›  专栏  ›  技术社区  ›  Jan

如何防止Matplotlib注释超出打印框架

  •  -1
  • Jan  · 技术社区  · 8 年前

    我尝试用其y轴值标记条形图( yy )在中 rotation=90 但有些低值超出了我的框架 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)
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Martin Evans    8 年前

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

    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