Matplotlib Add Color Legend With Value Based On Another Variable
I want to add color legend like this: Green - Tier 1 Gold - Tier 2 Silver - Tier 3 Chocolate - Tier 4. The values 'Tier 1', 'Tier 2', 'Tier 3', 'Tier 4' are based on another colu
Solution 1:
Seaborn's scatterplot
would automatically create a legend. The hue=
tells which column to use for coloring, the palette=
parameter tells the colors to use (either a list or a colormap). For non-numeric data, hue_order=
can fix a certain ordering.
Here is an example with toy data:
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
plt.style.use('classic')
N = 100
RFM = pd.DataFrame({'Tier': np.random.randint(1, 5, N),
'Monetary': np.random.uniform(1, 100, N),
'Recency': np.random.uniform(1, 500, N)})
color_palette = ['green', 'gold', 'silver', 'chocolate']
plt.figure(figsize=(10, 8))
ax = sns.scatterplot(data=RFM, x='Monetary', y='Recency', hue='Tier', palette=color_palette)
ax.set_title('Monetary and Recency Distribution', color='darkslategray')
plt.show()
PS: To change the legend labels, ax.legend
can be called explicitly, e.g.:
ax.legend([f'Tier {i}'for i inrange(1, 5)])
Post a Comment for "Matplotlib Add Color Legend With Value Based On Another Variable"