【问题标题】:How to customize pandas pie plot with labels and legend如何使用标签和图例自定义熊猫饼图
【发布时间】:2021-08-24 14:39:31
【问题描述】:

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

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”带到图表之外,并使用颜色在右上角创建一个图例?

【问题讨论】:

    标签: python pandas matplotlib pie-chart


    【解决方案1】:
    • 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()
    

    【讨论】:

    • 谢谢!!有效!!
    • @KwakuBiney 不客气。我很高兴这对你有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-31
    • 2014-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多