python - 如何在 Python 中更改饼图切片的顺序
问题描述
我想更改饼图中切片的顺序。目前,切片按降序排列。我希望图表的切片按以下顺序排列:是 > 有时 > 大部分时间 > 否
我正在使用以下代码:
colors = [ '#99f3bd', '#fbaccc','#a8df65', '#ff7b54']
fig, ax = plt.subplots(figsize=(5,15))
ax.set_title('Treatment Group', fontsize=25, fontname="Times New Roman Bold")
ax = df['q6_t'].value_counts(normalize=True).plot.pie(autopct='%1.0f%%', colors = colors)
ax.set_ylabel("")
plt.savefig('q6_t.png', bbox_inches = 'tight', transparent=True)
解决方案
我很惊讶我没有找到这个可能是常见问题的重复项。如果您想要饼图中的特定顺序,您必须对您的值计数生成的熊猫系列进行排序:
import matplotlib.pyplot as plt
import pandas as pd
#corresponding color-label pairs
colors = ['#99f3bd', '#fbaccc', '#a8df65', '#ff7b54']
labels = ["Yes", "Sometimes", "Most of the times", "No"]
#test data generation
import numpy as np
n=10
np.random.seed(1234)
df=pd.DataFrame({"A": np.random.random(n), "q6_t": np.random.choice(labels, n)})
#print(df)
fig, ax = plt.subplots(figsize=(8, 8))
ax.set_title('Treatment Group', fontsize=25, fontname="Times New Roman Bold")
#reindex(labels) sorts the index of the value counts according to the list labels
ax = df['q6_t'].value_counts(normalize=True).reindex(labels).plot.pie(autopct='%1.0f%%', colors = colors)
ax.set_ylabel("")
plt.show()
样本输出:
推荐阅读
- node.js - 从观察者触发器使用 Node.js require() 重新加载模块
- r - R:使用管道 %>% 和 pkg::fo 导致错误“.::base 中的错误:未使用的参数”
- python-3.x - 将字段内容转换为 Pandas DataFrame
- emacs - emacs 中的“历史”文件在哪里?
- mysql - 如何从mysql多对多选择中将单个值分组为数组?
- c++ - 迭代模板 int
- python - Python:七人制幸运游戏(平均掷骰数)
- telephony - 将 Zendesk 与“Hermes”电话系统集成
- amazon-web-services - 从 dotnet 核心代码中读取 AWS ECS 集群标签
- python - 超越关键字依赖的文本分类并推断实际含义