1

I'm trying to do some pie plot on the same categories for different conditions and I need that the results chart have always the same color.

enter image description here

enter image description here

For example here I need the same color for the rhinovirus in the two plots.

#!/usr/bin/env python3


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.read_csv('blast_results', sep='\t', names=['qseqid','sseqid','staxid','salltitles','length','pident','qstart','qend','sstart','send','qcovhsp','evalue','bitscore','qseq','sseq'])

#divide column
df[['sseqid', 'organism']] = df['sseqid'].str.split('|', 1, expand=True)
df['organism'] = df['organism'].str.split(':').str.get(1).astype(str).str.lower()

#add to salltitles the organism where not present
df['salltitles'] = np.where(df['organism']!='human', df['organism'] + ' ' +  df['salltitles'], df['salltitles'])

# divide column
df[['salltitles', 'strain','segment','host']] = df['salltitles'].str.split('|', 3, expand=True)

# remove unused column
df.drop(['organism','segment', 'staxid'], inplace=True, axis=1)


primers = df['qseqid'].unique()

for i in primers:
    print(i)
    subset = df[df['qseqid'] == i]
    subset[['salltitles', 'subtype']] = subset['salltitles'].str.split(' ', 1, expand=True)
    results = pd.DataFrame(subset.groupby('salltitles')['qseqid'].count())
    results.reset_index(inplace=True)
    results.sort_values('salltitles', inplace=True)
    x = [0.05 for i in range(0, results.shape[0])]
    explode = tuple(x)
    plt.figure()
    plt.pie(results['qseqid'], labels=results['salltitles'], autopct='%.1f%%', colors = ['#98F5FF', 'coral','#A2CD5A','#FF1493','#FF6EB4'], explode=explode)
    plt.title(i)

How can I specify the same color every time?

  • 1
    Did you have a look at this discussion : https://stackoverflow.com/questions/35206282/assign-specific-colours-to-data-in-matplotlib-pie-chart ? I feel like it could easily solve your problem – Beinje Jul 25 '22 at 14:25
  • Also I think you have a syntax error when defining your `colors` array within the for loop. And you don't use it in your last line of code. – Beinje Jul 25 '22 at 14:27
  • Yes! Thanks a lot! I didn't see that discussion before... – Denise Lavezzari Jul 26 '22 at 06:31

0 Answers0