Matplotlib饼图Mathtext标签/自动

2024-09-30 14:15:30 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我一直在玩弄pyplot pie()函数,它运行得很好,除了我尝试在楔形标记中使用mathtext时(如autoct标签中,我想要数字、一个\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()

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


Tags: 对象文本示例labelsmatplotlibasplt数字
1条回答
网友
1楼 · 发布于 2024-09-30 14:15:30

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

相关问题 更多 >

    热门问题