首页 > 解决方案 > 如何使用标签和图例自定义熊猫饼图

问题描述

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

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”移出图表并使用颜色在右上角创建图例?

标签: pythonpandasmatplotlibpie-chart

解决方案


  • legend=True adds the legend
  • title='Air Termination System' puts a title at the top
  • ylabel='' removes 'Air Termination System' from inside the plot. The label inside the plot was a result of radius=1.5
  • labeldistance=None removes the other labels since there is a legend.
  • If necessary, specify figsize=(width, height) inside data.plot(...)
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()

enter image description here


推荐阅读