Beth
Beth

Reputation: 55

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

Upvotes: 3

Views: 508

Answers (1)

Jake P
Jake P

Reputation: 480

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.

Upvotes: 2

Related Questions