如何仅显示数据中存在的图例中的类别
How to display only Categories in the legend present in the data
我的数据框如下:
在上面的数据框中,'Month'
是一个有序的 Categorical
列,定义为:
cats = ['January', 'February', 'March', 'April','May','June', 'July', 'August','September', 'October', 'November', 'December']
month_gr['Month'] = pd.Categorical(month_gr['Month'], cats, ordered = True)
使用 Seaborn 条形图:
ax = sns.barplot(data = month_gr, x = 'Item Name', y = 'Total', hue = 'Month')
ax.set_xticklabels(ax.get_xticklabels(), rotation= 90, ha = 'right')
输出:
上面的图例显示了 Categorical
列的所有 12 个月。我只想显示 4 个月 ['June', 'July', 'August', 'September']
的图例,因为我的数据只包含这 4 个月。有没有办法动态控制图例,使其仅显示传递给 data
的可用 Categories
?
您可以创建一个“已用月份”列表,然后将该列表设置为 hue_order
。这也确保只有那些月份会占用 space 条。
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
month_col = ['June'] * 5 + ['July'] * 5 + ['August'] * 5 + ['September'] * 7
month_gr = pd.DataFrame({'Month': month_col,
'Item Name': [*'abcdebdefgbcefgabcdefg'],
'Total': np.random.randint(100, 1000, len(month_col))})
cats = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
month_gr['Month'] = pd.Categorical(month_gr['Month'], cats, ordered=True)
used_months = [m for m in cats if m in month_gr['Month'].to_list()]
ax = sns.barplot(data=month_gr, x='Item Name', y='Total',
hue='Month', hue_order=used_months, palette=sns.color_palette("Set2"))
plt.show()
我的数据框如下:
在上面的数据框中,'Month'
是一个有序的 Categorical
列,定义为:
cats = ['January', 'February', 'March', 'April','May','June', 'July', 'August','September', 'October', 'November', 'December']
month_gr['Month'] = pd.Categorical(month_gr['Month'], cats, ordered = True)
使用 Seaborn 条形图:
ax = sns.barplot(data = month_gr, x = 'Item Name', y = 'Total', hue = 'Month')
ax.set_xticklabels(ax.get_xticklabels(), rotation= 90, ha = 'right')
输出:
上面的图例显示了 Categorical
列的所有 12 个月。我只想显示 4 个月 ['June', 'July', 'August', 'September']
的图例,因为我的数据只包含这 4 个月。有没有办法动态控制图例,使其仅显示传递给 data
的可用 Categories
?
您可以创建一个“已用月份”列表,然后将该列表设置为 hue_order
。这也确保只有那些月份会占用 space 条。
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
month_col = ['June'] * 5 + ['July'] * 5 + ['August'] * 5 + ['September'] * 7
month_gr = pd.DataFrame({'Month': month_col,
'Item Name': [*'abcdebdefgbcefgabcdefg'],
'Total': np.random.randint(100, 1000, len(month_col))})
cats = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
month_gr['Month'] = pd.Categorical(month_gr['Month'], cats, ordered=True)
used_months = [m for m in cats if m in month_gr['Month'].to_list()]
ax = sns.barplot(data=month_gr, x='Item Name', y='Total',
hue='Month', hue_order=used_months, palette=sns.color_palette("Set2"))
plt.show()