matplot pie: rotate labels horizontally

前端 未结 2 794
你的背包
你的背包 2021-01-06 12:03

Using matplot to create a little gauge with the code below:

    group_size=[10,10,10,10,10,50]
    labels=[\'AAAA\',\'BBBB\',\'CCCC\',\'DDDD\',\'EEEE\',\'\'         


        
2条回答
  •  庸人自扰
    2021-01-06 12:34

    My solution is basically similar to the accepted answer by ImportanceOfBeingErnest. But I think the steps involved are easier to grasp.

    import matplotlib.pyplot as plt
    
    group_size = [10, 10, 10, 10, 10, 50]
    labels = ['AAAA', 'BBBB', 'CCCC', 'DDDD', 'EEEE', '']
    fig, ax = plt.subplots()
    ax.axis('equal')
    pie = ax.pie(group_size, radius=2.2, colors=['k'], startangle=180, counterclock=False)
    
    # ax.pie() returns wedges, labels
    # Note that rotatelabels=False; so that, at this step ...
    # all labels are not rotated; they will be rotated later
    wedges, labels = ax.pie([10, 10, 10, 10, 10, 50], radius=2,  \
                          labeldistance=0.85, labels=labels, rotatelabels = False, \
                          startangle=180, counterclock=False)
    
    # do the rotation of the labels
    for ea, eb in zip(wedges, labels):
        mang =(ea.theta1 + ea.theta2)/2.  # get mean_angle of the wedge
        #print(mang, eb.get_rotation())
        eb.set_rotation(mang+270)         # rotate the label by (mean_angle + 270)
        eb.set_va("center")
        eb.set_ha("center")
    
    plt.show()
    

    The resulting image:

提交回复
热议问题