如何使用标签和图例自定义 pandas 饼图

How to customize pandas pie plot with labels and legend

尝试使用以下方法绘制饼图:

import pandas as pd
import numpy as np

data = {'City': ['KUMASI', 'ACCRA', 'ACCRA', 'ACCRA', 'KUMASI', 'ACCRA', 'ACCRA', 'ACCRA', 'ACCRA'], 'Building': ['Commercial', 'Commercial', 'Industrial', 'Commercial', 'Industrial', 'Commercial', 'Commercial', 'Commercial', 'Commercial'], 'LPL': ['NC', 'C', 'C', 'C', 'NC', 'C', 'NC', 'NC', 'NC'], 'Lgfd': ['NC', 'C', 'C', 'C', 'NC', 'C', 'NC', 'NC', 'C'], 'Location': ['NC', 'C', 'C', 'C', 'NC', 'C', 'C', 'NC', 'NC'], 'Hazard': ['NC', 'C', 'C', 'C', 'NC', 'C', 'C', 'NC', 'NC'], 'Inspection': ['NC', np.nan, np.nan, np.nan, 'NC', 'NC', 'C', 'C', 'C'], 'Name': ['Zonal', 'In Prog', 'Tullow Oil', 'XGI', 'Food Factory', 'MOH', 'EV', 'CSD', 'Electroland'], 'Air Termination System': ['Vertical Air Termination', 'Vertical Air Termination', 'Vertical Air Termination', 'Early Streamer Emission', 'Vertical Air Termination', 'Vertical Air Termination', 'Vertical Air Termination', 'Vertical Air Termination', 'Early Streamer Emission'], 'Positioned Using': ['Highest Points', 'Software', 'Software', 'Software', 'Highest Points', np.nan, np.nan, 'Rolling Sphere Method', 'Software']}
df = pd.DataFrame(data)

colors = ['#ff9999','#66b3ff','#99ff99','#ffcc99']
data = df["Air Termination System"].value_counts().plot(kind="pie",autopct='%1.1f%%', radius=1.5, shadow=True, explode=[0.05, 0.05], colors=colors)

当前图表如下:

如何将标题“Air Termination Systems”移出图表并使用颜色在右上角创建图例?

  • legend=True 添加图例
  • title='Air Termination System' 将标题放在顶部
  • ylabel='' 从图中删除 'Air Termination System'。图中的标签是 radius=1.5
  • 的结果
  • labeldistance=None 删除其他标签,因为有图例。
  • 如有必要,在data.plot(...)
  • 中指定figsize=(width, height)
colors = ['#ff9999','#66b3ff','#99ff99','#ffcc99']
data = df["Air Termination System"].value_counts()
ax = data.plot(kind="pie", autopct='%1.1f%%', shadow=True, explode=[0.05, 0.05], colors=colors, legend=True, title='Air Termination System', ylabel='', labeldistance=None)
ax.legend(bbox_to_anchor=(1, 1.02), loc='upper left')
plt.show()