Jul-12-2019, 10:27 AM
How can I make each slice of the pie chart have a different colour?
![[Image: iCheY7e.png]](https://i.imgur.com/iCheY7e.png)
this is the code:
![[Image: Lf2GPug.png]](https://i.imgur.com/Lf2GPug.png)
I think the colours are grouped together because the intervals produced by colornorm are too close together. I've tried multiplying i by numbers like 2 and 4, which works, until i exceeds the numbers of colours in the set, and then all the colours are mapped to vmax (which i've defined as the length of the list of industries in the data). increasing the vmax value by a corresponding amount just re-presents the issue.
Is there a better way of doing this?
![[Image: iCheY7e.png]](https://i.imgur.com/iCheY7e.png)
this is the code:
import pandas as pd import matplotlib from matplotlib import pyplot as plt #the data is taken from a sql database data = pd.read_sql(sql,connection) not_null_industry = data[pd.notnull(data['Industry'])] not_null_industry['count'] = 1 count = not_null_industry.groupby(['Industry']).count()['count'] industries = not_null_industry['Industry'].unique() industries.sort() deals = count.values #map industry to number of deals to keep colors consistent later industry_deals = {} for (industry,deal) in zip(industries,deals): industry_deals[industry] = deal #turn dictionary into list of tuples to pass into pie chart later sorted_deals = sorted(industry_deals.items(),key=lambda x:x[1],reverse=True) #split industries from number of deals to pass into the pie chart sorted_industries = [x[0] for x in sorted_deals] sorted_values = [x[1] for x in sorted_deals] colormap = plt.cm.get_cmap('Set1') colornorm = matplotlib.colors.Normalize(vmin=0.0,vmax=len(industries)) colors = [] #assign a color to each industry and the corresponding patch in the legend handles = [] for i,l in enumerate(industries): handles.append(matplotlib.patches.Patch(color=plt.cm.Set1((colornorm((i)))))) colors.append(colormap((colornorm(i)))) print(colornorm(i)) #pass split value into pie chart patches, texts = plt.pie(sorted_values,colors=colors,startangle=90) plt.legend(handles,sorted_industries, bbox_to_anchor=(0.85,1.025),loc='upper left') plt.axis('equal') plt.tight_layout() plt.show()this is the output of printing the color normalisations:
![[Image: Lf2GPug.png]](https://i.imgur.com/Lf2GPug.png)
I think the colours are grouped together because the intervals produced by colornorm are too close together. I've tried multiplying i by numbers like 2 and 4, which works, until i exceeds the numbers of colours in the set, and then all the colours are mapped to vmax (which i've defined as the length of the list of industries in the data). increasing the vmax value by a corresponding amount just re-presents the issue.
Is there a better way of doing this?