我想在饼图中将标签从中心移动到每个楔形块的开始:

import matplotlib.pyplot as plt
 
# Setting labels for items in Chart
Employee = ['A', 'B', 'C',
            'D', 'E']
 
# Setting size in Chart based on 
# given values
Salary = [40000, 50000, 70000, 54000, 44000]
 
# colors
colors = ['#FF0000', '#0000FF', '#FFFF00', 
          '#ADFF2F', '#FFA500']
fig, ax = plt.subplots(figsize=(5,5), facecolor = "#FFFFFF")
# Pie Chart
wedges, texts = ax.pie(Salary, colors=colors, 
        labels=Employee, labeldistance=0.8,
        wedgeprops=dict(width=0.35),)

我可以获得标签的坐标,并将其替换为:

for lbl,p in zip(Employee,texts, ):
        x, y = p.get_position()
        print(x,y,p)
        ax.annotate(lbl, xy=(x,y),  size=12, color = "w")

但我不知道如何移动它们来跟随圆圈.

我也可以得到每个楔形开始的Angular 调用楔形属性,但由于饼图是绘制在笛卡尔轴而不是极轴上,我不知道如何?

我不能用barh来做这个(我的图表比这里显示的要复杂).

这可能吗?

这就是我想要标签的位置.

enter image description here

推荐答案

您可以根据楔形块的属性自行计算标签的位置,添加一个小的Angular 偏移(此处为10 °):

import numpy as np

wedges, texts = ax.pie(Salary, colors=colors, 
        #labels=Employee, labeldistance=0.8,
        wedgeprops=dict(width=0.35),)

shift = 10

for lbl, w in zip(Employee, wedges):
    angle = w.theta2 - shift
    r = 0.8                          # convert polar to cartesian
    x = r*np.cos(np.deg2rad(angle))  #
    y = r*np.sin(np.deg2rad(angle))  #
    ax.annotate(lbl, xy=(x,y), size=12, color='w',
                ha='center', va='center', weight='bold')

输出:

matplotlib pie plot label annotation start of wedge

为了更好的可视性:

import matplotlib.patheffects as pe
for lbl, w in zip(Employee, wedges):
    angle = w.theta2-10
    r = 0.8
    print(lbl, angle, np.deg2rad(angle))
    x = r*np.cos(np.deg2rad(angle))
    y = r*np.sin(np.deg2rad(angle))
    ax.annotate(lbl, xy=(x,y), size=12, color='w',
                ha='center', va='center', weight='bold',
                path_effects=[pe.withStroke(linewidth=2, foreground='k')]
               )

matplotlib pie plot label annotation start of wedge with text outline

Python相关问答推荐

2维数组9x9,不使用numpy.数组(MutableSequence的子类)

试图找到Python方法来部分填充numpy数组

根据在同一数据框中的查找向数据框添加值

如何避免Chained when/then分配中的Mypy不兼容类型警告?

无法使用requests或Selenium抓取一个href链接

无法定位元素错误404

Pandas—合并数据帧,在公共列上保留非空值,在另一列上保留平均值

在含噪声的3D点网格中识别4连通点模式

如何在图中标记平均点?

在pandas/python中计数嵌套类别

Django Table—如果项目是唯一的,则单行

在极点中读取、扫描和接收有什么不同?

裁剪数字.nd数组引发-ValueError:无法将空图像写入JPEG

来自Airflow Connection的额外参数

Django.core.exceptions.SynchronousOnlyOperation您不能从异步上下文中调用它-请使用线程或SYNC_TO_ASYNC

为什么我只用exec()函数运行了一次文件,而Python却运行了两次?

Polars定制函数返回多列

解析CSV文件以将详细信息添加到XML文件

删除另一个div中的特定div容器

如何让PYTHON上的Selify连接到现有的Firefox实例-我无法连接到Marionette端口