How to add arrows to labels and percentages in pie chart?

65 Views Asked by At

I want to make a pie chart with Matplotlib similar to the one in the image below.

(https://i.stack.imgur.com/ZDm8z.png)

I have mainly two problems:

  1. I cannot align the labels and the percentage values.
  2. I cannot point the arrows to the side of the labels.

I have tried aligning the percentage (autotext) to the position of the labels by changing the x position, but seems to be different. My script looks like this:

plot_type == 'pie':
        labels = data.iloc[2:, 1]
        values = data.iloc[2:, 2].astype(float)

        fig1, ax = plt.subplots(figsize=(8, 6), subplot_kw=dict(aspect="equal"))
        palette_color = sns.color_palette('RdBu_r')
        wedges, texts, autotext = ax.pie(values, startangle=90,colors=palette_color, wedgeprops={'edgecolor':'w','linewidth':2}, textprops={'family':'Noto Sans','fontsize': 12}, autopct='%1.1f%%')

        kw = dict(arrowprops=dict(arrowstyle="-"), va="center")
        for p, label, autotext in zip(wedges, labels, autotext):
            ang = np.deg2rad((p.theta1 + p.theta2) / 2)
            y = np.sin(ang)
            x = np.cos(ang)
            horizontalalignment = "center" if abs(x) < abs(y) else "right" if x < 0 else "left"
            ann=ax.annotate(label, xy=(0.9 * x, 0.9 * y), xytext=(1.3 * x, 1.3 * y),
                        horizontalalignment=horizontalalignment, **kw)

            enx=ann.get_position()[0]
            autotext.set_fontsize(12)
            autotext.set_x(enx)  # set x position relative to label
            autotext.set_y(ann.get_position()[1] + 0.1)  # adjust vertical position

        plt.title(title, fontsize=12, fontname='Noto Sans')
        plt.tight_layout()
        plt.show()

My figure looks like this:

(https://i.stack.imgur.com/Lp10a.png)

Can the 2nd issue be solved with arrowprops?

0

There are 0 best solutions below