Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中更改饼图切片的顺序_Python_Pandas_Matplotlib_Data Analysis - Fatal编程技术网

如何在Python中更改饼图切片的顺序

如何在Python中更改饼图切片的顺序,python,pandas,matplotlib,data-analysis,Python,Pandas,Matplotlib,Data Analysis,我想更改饼图中切片的顺序。目前,切片按降序排列。我希望图表的切片按以下顺序排列: 是>有时>大多数时候>否 我正在使用以下代码: 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 =

我想更改饼图中切片的顺序。目前,切片按降序排列。我希望图表的切片按以下顺序排列: 是>有时>大多数时候>否

我正在使用以下代码:

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()
样本输出: