如何使用Python手动向matplotlib添加标签

问题描述 投票:0回答:1

我正在尝试将labels手动添加到我的seaborn plot,但这未输出标签

这是我的dataframe的样子:

import pandas as pd
df = pd.DataFrame({'Product_ID': ['20','23', '20','24','24', '24', '24', '24','24', '20'],
 'ProductNames': ['Gem','Wil', 'Gem','Wefdem','Wefdem','Wefdem', 'Wefdem', 'Wefdem', 'Wefdem','Gem']})

这是我要打印和手动添加标签的项目

# It is a large dataframe, this is just a subset thats why I selected the first largest 10 with nlargest

order=df["Product_ID"].value_counts().nlargest(10).index

# again the actual dictionary is larger than this, this is just a shorter one of it
product_keys = {"20": "Gem", "23": "Wil", "24": "Wefdem"}

plt.figure(figsize=(20,20))
g = sns.countplot(df["Product_ID"], order=order)
g.axes.set_title("Most popular IDs", fontsize=40)
g.axes.set_xlabel("Product IDs", fontsize=30)
g.axes.set_ylabel("Frequency count", fontsize=30)
g.tick_params(labelsize=24)

plt.legend([g], [product_keys[key] for key in order]) # <--- This does not work or shows only one label

请问如何解决这个问题?

python dataframe matplotlib bar-chart seaborn
1个回答
0
投票

seaborn docs表示

order,字符串的hue_orderlists,可选为了绘制分类级别,否则从数据对象推断级别。

缠住你的头的是,Seaborn与matplotlib中的对象进行了接口。因此,我建议先学习matplotlib,然后再研究seaborn。 countplot功能查找由plt.figure创建的活动图形。 hue参数在数据框第二列中的数据中查找级别。

我冒昧地使您的代码更具Pythonic:

import pandas as pd
df = pd.DataFrame({'Product_ID': ['20','23', '20','24','24', '24', '24', '24','24', '20'],
 'ProductNames': ['Gem','Wil', 'Gem','Wefdem','Wefdem','Wefdem', 'Wefdem', 'Wefdem', 'Wefdem','Gem']})

import matplotlib.pyplot as plt,\
seaborn as sns
order=df["Product_ID"].value_counts().nlargest(10).index

# again the actual dictionary is larger than this, this is just a shorter one of it
product_keys = {"20": "Gem", "23": "Wil", "24": "Wefdem"}
fig, ax = plt.subplots()
sns.countplot(x = "Product_ID", data = df,\
              order = order, ax = ax,\
              hue = "ProductNames" )
ax.set_title("Most popular IDs", fontsize=40)
ax.set_xlabel("Product IDs", fontsize=30)
ax.set_ylabel("Frequency count", fontsize=30)
ax.axes.tick_params(labelsize=24)
fig.show()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.