matplotlib pie chart label order code example

Example: matplotlib pie chart label order

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()