Matplotlib基于另一个变量添加带有颜色值的颜色图例 [英] 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.
值层1",层2",层3",层4"基于另一个称为 RFM ['Tier']
的列.
The values 'Tier 1', 'Tier 2', 'Tier 3', 'Tier 4' are based on another column called RFM['Tier']
.
plt.style.use('classic')
#Scatter plot monetary and recency
Color = ['green','gold','silver','chocolate']
RFM['Color']= RFM['Cluster'].map(lambda p: Color[p])
ax = RFM.plot(
kind='scatter',
x='Monetary', y='Recency',
figsize=(10,8),
c= RFM['Color']
)
ax.set_title('Monetary and Recency Distribution',color='darkslategray')
推荐答案
Seaborn的散点图
将自动创建图例.hue=
告诉要使用哪一列着色,palette=
参数告诉要使用的颜色(列表或颜色图).对于非数字数据,hue_order=
可以固定某种顺序.
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:要更改图例标签,可以显式调用 ax.legend
,例如:
PS: To change the legend labels, ax.legend
can be called explicitly, e.g.:
ax.legend([f'Tier {i}' for i in range(1, 5)])
这篇关于Matplotlib基于另一个变量添加带有颜色值的颜色图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!