Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib Donut Labels/Annotation position

I am trying to recreate this exact style of this donut chart, but I can't figure out how to adjust the labels/annotations to be in this same position and underlined.

enter image description here

I found an annotation program example online, but I don't understand it enough to make the necessary adjustments.

fig, ax = plt.subplots(figsize=(6, 3), subplot_kw=dict(aspect="equal"))

labels= 'x', 'y'

data = [1266.97, 746.79 ]  

wedges, texts = ax.pie(data, wedgeprops=dict(width=0.5), startangle=225)

kw = dict(arrowprops=dict(arrowstyle="-"),
           zorder=0, va="center")

for i, p in enumerate(wedges):
    ang = (p.theta2 - p.theta1)/2. + p.theta1
    y = np.sin(np.deg2rad(ang))
    x = np.cos(np.deg2rad(ang))
    horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]
    connectionstyle = "angle,angleA=0,angleB={}".format(ang)
    kw["arrowprops"].update({"connectionstyle": connectionstyle})
    ax.annotate(data[i], xy=(x, y), xytext=(1.35*np.sign(x), 1.4*y),
                horizontalalignment=horizontalalignment,  **kw)

ax.set_title("title")

plt.show()

The above code creates the following donut, but I can't figure out how to adjust my label lines to match the above example.

enter image description here

like image 314
Beth Avatar asked Sep 19 '26 03:09

Beth


1 Answers

You are determining the position of the labels with these lines:

y = np.sin(np.deg2rad(ang))
x = np.cos(np.deg2rad(ang))

You can instead set the position of the text manually like so:

annotation_postions = [(-.5, .5), (.5, .5)]
for i, p in enumerate(wedges):
    ang = (p.theta2 - p.theta1) / 2. + p.theta1
    print(i)
    y = annotation_postions[i][1]
    x = annotation_postions[i][0]
    horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]
    connectionstyle = "angle,angleA=0,angleB={}".format(ang)
    kw["arrowprops"].update({"connectionstyle": connectionstyle})
    ax.annotate(data[i], xy=(x, y), xytext=(3*x, 1 * y),
                horizontalalignment=horizontalalignment, **kw)

xy is where the line starts on the chart.

xytext is where the text is located

The underline is just the line extending below the text. You'll have to research how to make it longer and put the text ontop of it.

like image 150
Jake P Avatar answered Sep 23 '26 04:09

Jake P