Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Spacing pie chart colours evenly in matplotlib?
How can I make each slice of the pie chart have a different colour?


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()
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 ='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):
#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')
this is the output of printing the color normalisations:

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?
I think the main problem here is that you were used the Set1 colormap. This colormap can handle only 9 colors. Consider using continuous colormap, e.g. bwr or something else.

Top Page

Forum Jump:

Users browsing this thread: 1 Guest(s)