如何自定义pandas饼图的标题位置及右上角图例
解决方案
你可以通过调用matplotlib的标题、图例配置接口实现需求,完整修改后的代码如下:
import pandas as pd import numpy as np import matplotlib.pyplot as plt 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'] # 统计类别数量 system_count = df["Air Termination System"].value_counts() # 绘制饼图,关闭默认y轴标签避免显示重复标题 ax = system_count.plot(kind="pie",autopct='%1.1f%%', radius=1.5, shadow=True, explode=[0.05, 0.05], colors=colors, ylabel='') # 设置标题,调整y参数将标题移到饼图外侧上方 plt.title("Air Termination Systems", y=2.0) # 添加上角图例,使用统计得到的类别名作为标签,调整位置避免和饼图重叠 plt.legend(labels=system_count.index, loc='upper right', bbox_to_anchor=(1.3, 1)) # 自动调整布局避免内容被截断 plt.tight_layout() plt.show()
关键修改说明
- 绘图时添加
ylabel=''参数,移除pandas绘图默认渲染的列名字样,避免标题重复 - 通过
plt.title的y参数调整标题垂直位置,数值越大标题位置越高,适配你设置的1.5倍饼图半径 - 通过
plt.legend指定图例位置为右上角,用bbox_to_anchor调整图例的绝对坐标,避免和饼图、百分比标签重叠,图例配色会自动继承你设置的colors变量
内容的提问来源于stack exchange,提问作者Kwaku Biney
相关产品推荐
相关产品推荐

