【问题标题】:matplot pie: rotate labels horizontallymatplotlib pie:水平旋转标签
【发布时间】:2018-10-18 12:45:43
【问题描述】:

使用 matplot 创建一个小量规,代码如下:

    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)
    pie2 = ax.pie([10,10,10,10,10,50], radius=2,  labeldistance=0.7, labels=labels, rotatelabels = 270,
startangle=180,counterclock=False)
    plt.show()

我试图让标签水平移动并与每个楔形的中点对齐(但与楔形内的文本):

使用 rotatelabel=True,我得到以下信息:

关于如何实现图表标签水平旋转的任何想法?

【问题讨论】:

    标签: python matplotlib data-visualization pie-chart


    【解决方案1】:

    您需要手动旋转饼图标签。为此,您可以遍历标签并根据需要设置旋转。

    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)
    pie2 = ax.pie([10,10,10,10,10,50], radius=2,  labeldistance=0.9, labels=labels, 
                  rotatelabels =True, startangle=180,counterclock=False)
    
    plt.setp(pie2[1], rotation_mode="anchor", ha="center", va="center")
    for tx in pie2[1]:
        rot = tx.get_rotation()
        tx.set_rotation(rot+90+(1-rot//180)*180)
    
    plt.show()
    

    【讨论】:

      【解决方案2】:

      我的解决方案与ImportanceOfBeingErnest 接受的答案基本相似。但我认为所涉及的步骤更容易掌握。

      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()
      

      生成的图像:

      【讨论】:

        猜你喜欢
        • 2016-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-08
        • 1970-01-01
        • 2017-12-26
        相关资源
        最近更新 更多