Page 12 sur 25
Pie Chart
Simple pie
If you have a data-frame with fields Categories and Total, you can create a pie chart.
[code]import matplotlib.pyplot as plt
chartLabel = df_Categories_count['Categories'].tolist()
chartValue = df_Categories_count['Total'].tolist()
colors = plt.rcParams['axes.prop_cycle'].by_key()['color']
fig1 = plt.figure()
plt.pie(chartValue, labels=chartLabel, colors=colors, autopct=None, shadow=False, startangle=90)
plt.axis('equal')
plt.title('Categories', pad=20, fontsize=15)
plt.show()
plt.clf()[/code]
Display percentages in the chart
Use autopct.
[code]plt.pie(chartValue, labels=chartLabel, colors=colors, autopct='%1.1f%%', shadow=False, startangle=90)[/code]
Change the labels font size
[code]plt.rcParams['font.size'] = 5[/code]
Hide a label in chart
Just replace the value with an empty string.
[code]chartLabel[-1] = ''[/code]
Add a legend in your chart
[code]plt.legend(chartLabel, loc='best', fontsize=8)[/code]
Explode
To explode your chart, you need to pass values in explode, example if you have 4 values to plot:
[code]plt.pie(myValue, labels=myLabels, colors=colors, explode=[0.05, 0.05, 0.05, 0.05], autopct=None, shadow=False, startangle=90)[/code]
If you want explode all part by default, just create a list before:
[code]explodeValues = []
for i in myValue:
explodeValues.append(0.05)
plt.pie(myValue, labels=myLabels, colors=colors, explode=explodeValues, autopct=None, shadow=False, startangle=90)[/code]
Add a legend with several fields
For example you want display labels and percentages in the legend. First calculate percentages in another field in your data-frame, then:
[code]import matplotlib.pyplot as plt
chartLabel = df_Categories_count['Categories'].tolist()
chartLegendLabel = df_Categories_count['Categories'].tolist()
chartValue = df_Categories_count['Total'].tolist()
chartLegendPercent = df_Categories_count['Percent'].tolist()
legendLabels = []
for i, j in zip(chartLegendLabel, map(str, chartLegendPercent)):
legendLabels.append(i + ' (' + j + ' %)')
colors = plt.rcParams['axes.prop_cycle'].by_key()['color']
fig1 = plt.figure()
plt.pie(chartValue, labels=chartLabel, colors=colors, autopct=None, shadow=False, startangle=90)
plt.axis('equal')
plt.title('Categories', pad=20, fontsize=15)
plt.legend(legendLabels, loc='best', fontsize=8)
plt.show()
plt.clf()[/code]