Skip to content Skip to sidebar Skip to footer

How To Set Unique Color For Individual Value Of Legend

I have many legends in my stacked bar plot and I noticed that in legend the color is repeating so it's hard for me to distinguish the true value in the graph according to the legen

Solution 1:

You might create a list of colors with the same length as the number of unique complaints. For example gist_ncar. In the code I shuffled the order of the colors to make it less likely that similar colors are near.

Note that it is very hard to have more than 20 colors that are different enough visually. Different people and different monitors may cause colors hard to distinguish.

This and this post provide more ideas to choose enough colors. In your case it might be interesting to color similar complaints with similar hues.

As your example code doesn't provide enough data, the code below generates some random numbers.

import pandas as pd
from matplotlib import pyplot as plt
import random
import matplotlib as mpl

city = ['Londen', 'Paris', 'Rome', 'Brussels', 'Cologne', 'Madrid',
        'Athens', 'Geneva', 'Oslo', 'Barcelona', 'Berlin']
complaints = list('abcdefghijklmnopqrstuv')

N = 100
city_column = random.choices(city, k=N)
complaints_column = random.choices(complaints, k=N)
test2 = pd.DataFrame({'City': city_column, 'Complaint Type': complaints_column})

# take a colormap with many different colors and sample it at regular intervals
cmap = plt.cm.gist_rainbow
norm = mpl.colors.Normalize(vmin=0, vmax=len(complaints) - 1)
colors = [cmap(norm(i)) for i inrange(len(complaints))]

# create a stack bar chart
cmpltnt_rela = test2.groupby(['City', 'Complaint Type']).size().unstack().fillna(0).plot(kind='bar',
      legend=True, stacked=True, color=colors)
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5), ncol=2)
cmpltnt_rela.plot(figsize=(18, 14))
plt.tick_params('x', labelrotation=30)

plt.tight_layout()
plt.show()

example plot

Post a Comment for "How To Set Unique Color For Individual Value Of Legend"