【问题标题】:Matplotlib Pie Chart Mathtext Label/AutopctMatplotlib 饼图 Mathtext 标签/Autopct
【发布时间】:2015-08-28 15:00:50
【问题描述】:

所以我一直在玩弄 pyplot pie() 函数,它运行良好,除了我尝试在楔形标记中使用 mathtext 时(如在 autopct 标记中,我想要数字,一个 \pm (+-) 符号和一些相关的数字)。可以简单地做到这一点吗?我是否必须拉出所有楔形对象并操纵它们的文本(可能本身就是一系列文本对象)还是有一些更简单的方法?我不介意一些复杂性,我真的很想能够做到这一点。

编辑:一个示例将是 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()

我们的想法是让 autopct 格式关键字生成的数字以 +- 和一些数字结尾。

【问题讨论】:

  • 一个你正在做的小例子让问题更容易理解/回答。

标签: python text matplotlib pie-chart tex


【解决方案1】:

我不确定您的问题是与 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

【讨论】:

  • 好吧,我没有详细说明,因为我只是想知道它是否可以完成。它当然可以,很明显。