matplotlib Seaborn histplot图例中的重复标签

bcs8qyzn  于 2023-08-06  发布在  其他
关注(0)|答案(1)|浏览(93)

我试图用两个数据集生成一个组合的histplot,代码如下

_,bins = np.histogram([150, 600], bins=30)
alpha = 0.4

fig, ax = plt.subplots(1,1)
sns.histplot(df1['Tm/K Pred.'], bins=bins, alpha=alpha, label='df1')
sns.histplot(vispilsExp298Tm_bert['Tm/K Pred.'], bins=bins, alpha=alpha, label='df2')

plt.yscale('log')
plt.legend()
plt.show()

字符串


的数据
但是,图例中的标签是重复的。我能问一下我怎样才能把它们去掉吗??
我查了一下:

handles, labels = ax.get_legend_handles_labels()
handles, labels
([<BarContainer object of 1 artists>,
  <BarContainer object of 30 artists>,
  <BarContainer object of 1 artists>,
  <BarContainer object of 30 artists>],
 ['df1', 'df1', 'df2', 'df2'])

的数据

6mw9ycah

6mw9ycah1#

您可以使用字典删除重复的标签:

lgd, keys = ax.get_legend_handles_labels()
d = dict(zip(keys, lgd))
plt.legend(d.values(), d.keys())

字符串
输出量:


的数据
或者,合并数据集并让seaborn处理图例怎么样?

import pandas as pd

sns.histplot(pd.concat({'df1': df1[['Tm/K Pred.']],
                        'df2': vispilsExp298Tm_bert[['Tm/K Pred.']]},
                       names=['dataset']).reset_index('dataset'),
             x='Tm/K Pred.', hue='dataset', bins=bins, alpha=alpha,
             hue_order=['df2', 'df1']
            )



如果没有Pandas:

sns.histplot({'df1': df1['Tm/K Pred.'],
              'df2': vispilsExp298Tm_bert['Tm/K Pred.']},
             bins=bins, alpha=alpha,
             hue_order=['df2', 'df1']
            )


输出量:


相关问题