python - 如何使用标签和图例自定义熊猫饼图
问题描述
尝试使用以下方法绘制饼图:
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
adds the legendtitle='Air Termination System'
puts a title at the topylabel=''
removes'Air Termination System'
from inside the plot. The label inside the plot was a result ofradius=1.5
labeldistance=None
removes the other labels since there is a legend.- If necessary, specify
figsize=(width, height)
insidedata.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()
推荐阅读
- python - 如何使用 Python 3.8 alpha 中引入的赋值表达式重写这个简单的循环?
- google-play - 在 Google Play 上下载不同的测试版本
- python - 用于显示一个图形的 Python 子图
- r - 将拟合 Cox 模型与 R 中的 cluster() 元素进行比较
- reactjs - 模态 - onChange 事件
- redis - 加入 Redis 流
- spring-kafka - Spring Kafka bean 返回类型
- javascript - 在 Redux 中调度多个异步操作的正确方法
- python - 不明白为什么总是给我一个错误
- javascript - 在反应组件中全局更改颜色的最有效方法是什么?