首页 > 解决方案 > Python:增加饼图中文本标签之间的间距

问题描述

我正在可视化情绪分析的结果,但一些标签重叠 - 如何增加(某些)文本标签之间的空间,例如“爱”和“惊喜”?

非常感谢任何帮助!

数据重现图:

# 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()

生成的饼图: 饼图

标签: pythonmatplotlibpie-chart

解决方案


推荐阅读