python + matplotlib: barh plot show incomplete YTick labels - how to dynamically move the plot area to the right to fit the given YTickLabels?

后端 未结 2 1387
野的像风
野的像风 2021-01-13 14:00

I\'m using matplotlib to plot a barh plot to a file. Unfortunate, the YTickLaels are a bit too long and the plot area won\'t move to the right auto

相关标签:
2条回答
  • 2021-01-13 14:48

    According to matplotlib mailing list, there is no automatic way of doing this. However, you can manually ajdust subplot padding by using figure.subplots_adjust method. Placing fig.subplots_adjust(left = 0.4) after ax = fig.add_subplot(111) in your code yields following result:

    enter image description here

    0 讨论(0)
  • 2021-01-13 14:51

    Actually, there is an automatic way of doing this now: tight_layout.

    In your case:

    import matplotlib as mpl
    mpl.use('Agg')
    import matplotlib.pyplot as plt
    D = {u'Label1':26, u'Label2 is longer than others': 17, 
         u'Label3 is not so short either':30}
    fig = plt.figure(figsize=(5.5,3),dpi=300)
    ax = fig.add_subplot(111)
    ax.grid(True,which='both')
    bar = ax.barh(range(1,len(D)+1,1),D.values(),0.4,align='center')
    plt.yticks(range(1,len(D)+1,1), D.keys(), size='small')
    fig.tight_layout() # <---- ADD THIS
    fig.savefig('D_bar.png')
    
    0 讨论(0)
提交回复
热议问题