Text alignment in a Matplotlib legend

前端 未结 2 1686
臣服心动
臣服心动 2020-12-14 19:21

I am trying to right-align the entries in a matplotlib axes legend (by default they are left-aligned), but can\'t seem to find any way of doing this. The setup I have is bel

相关标签:
2条回答
  • 2020-12-14 19:55

    I tried to get the example work, but I couldn't.

    At least since matplotlib version 1.1.1 (maybe earlier) we need a dedicated renderer instance. Take care of your backend which defines the renderer. Depending on backend the output may look fine on screen but dismal as PDF.

    # get the width of your widest label, since every label will need 
    #to shift by this amount after we align to the right
    renderer = figure.canvas.get_renderer()
    shift = max([t.get_window_extent(renderer).width for t in legend.get_texts()])
    for t in legend.get_texts():
        t.set_ha('right') # ha is alias for horizontalalignment
        t.set_position((shift,0))
    
    0 讨论(0)
  • 2020-12-14 20:15

    The backdoor you're looking for is the following:

    # get the width of your widest label, since every label will need 
    # to shift by this amount after we align to the right
    shift = max([t.get_window_extent().width for t in legend.get_texts()])
    for t in legend.get_texts():
        t.set_ha('right') # ha is alias for horizontalalignment
        t.set_position((shift,0))
    
    0 讨论(0)
提交回复
热议问题