代码之家  ›  专栏  ›  技术社区  ›  Scheme stepper

Matplotlib饼图数学文本标签/Autopct

  •  1
  • Scheme stepper  · 技术社区  · 9 年前

    所以我一直在摆弄pyplot pie()函数,它工作得很好,除了我尝试在楔形标签中使用mathtext(就像在autoct标签中一样,我想要数字、一个\pm(+-)符号和一些相关的数字)。是否可以简单地做到这一点?我需要拉出所有的楔形对象并操纵它们的文本(可能本身就是一系列文本对象)还是有一些更简单的方法?我不介意一些复杂性,我只想能够做到这一点。

    edit:一个示例是matplotlib代码库中的第一个饼图示例:

    import matplotlib.pyplot as plt
    
    
    # The slices will be ordered and plotted counter-clockwise.
    labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
    sizes = [15, 30, 45, 10]
    colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
    explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')
    
    plt.pie(sizes, explode=explode, labels=labels, colors=colors,
            autopct='%1.1f%%', shadow=True, startangle=90)
    # Set aspect ratio to be equal so that pie is drawn as a circle.
    plt.axis('equal')
    
    plt.show()
    

    这个想法是让autoct格式关键字生成的数字以+和一些数字结尾。

    1 回复  |  直到 9 年前
        1
  •  4
  •   Diziet Asahi    9 年前

    我不确定你的问题是mathtext还是仅仅是创建自定义标签。此外,你没有说你想在±号后面的值是从哪里得到的。

    这里我假设您有一个列表,其中包含要为每个楔形添加的值。

    # The slices will be ordered and plotted counter-clockwise.
    labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
    sizes = [15, 30, 45, 10]
    colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
    explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')
    
    patches, texts, autotexts = plt.pie(sizes, explode=explode, labels=labels, colors=colors,
            autopct='%1.1f%%', shadow=True, startangle=90)
    # Set aspect ratio to be equal so that pie is drawn as a circle.
    plt.axis('equal')
    
    
    otherInfo = [3, 5, 3, 4]
    
    for text, info in zip(autotexts, otherInfo):
        text.set_text(u"%s ± %.1f" % (text.get_text(), info)) #you can play here with the format to get the label that you want
    

    enter image description here