0

I'm visualizing the results from a sentiment analysis but some labels are overlapping - how can I increase the spaces between (some of) the text labels, such as 'love' and 'surprise'?

Any help is highly appreciated!

Data to reproduce figure:

# Import packages
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

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

# Data
percent = [89.57, 5.12, 1.67, 3.06, 0.39, 0.19]
labels = ["joy: 89.57%", "anger: 5.12%", "sadness: 1.67%", "fear: 3.06%", "surprise: 0.39%", "love: 0.19%"]
colors = ['#66b3ff','#ff9999','#99ff99','#ffcc99', 'purple', 'green']

# Pie plot
wedges, texts = ax.pie(percent, startangle=-40, colors = colors, labeldistance=1.5,wedgeprops = { 'linewidth' : 1, 'edgecolor' : 'white' }) # ax.pie both returns a sequence of matplotlib.patches.Wedge instances and alist of the label matplotlib.text.Text instances

# Adding lines to text
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))
    print(ang)
    horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]
    connectionstyle = f"angle,angleA=1,angleB={ang}"
    kw["arrowprops"].update({"connectionstyle": connectionstyle})
    
    ax.annotate(labels[i], xy=(x, y), xytext=(1.50*np.sign(x), 1.3*y),
               horizontalalignment=horizontalalignment, 
                **kw)

plt.show()

Resulting pie plot: Pie plot

mar_mor97
  • 3
  • 3

0 Answers0