首页 > 解决方案 > sns.catplot,缩小条形之间的差距

问题描述

这是我运行此代码时得到的情节有什么办法可以减少这两个条之间的间隙但不能完全相互接触?

sns.catplot(x = "case", kind = "count", data = df, alpha=0.8, palette = my_pal, hue="class")
plt.ylabel("Count", size=12)
plt.tight_layout()

在此处输入图像描述

标签: pythonmatplotlibseabornlegend

解决方案


问题似乎是“case”和“class”列包含相同的信息,只是名称不同。在 case 为 1 的任何地方,class 都是 Negative,反之亦然。

如果您同时使用xand hue,seaborn 将放置 4 列:

  • 案例 1,“负面”类
  • 案例 1,“绿色”类
  • 案例 2,“负面”类
  • 案例 2,“绿色”类

四列中的两列保持空白:

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df = pd.DataFrame({'case': np.concatenate([np.repeat([1], 3700), np.repeat([2], 1200)]),
                   'class': np.concatenate([np.repeat(['Negative'], 3700), np.repeat(['green'], 1200)])})

g = sns.catplot(x="case",
                hue='class',
                palette='Blues',
                data=df,
                kind="count")
plt.show()

演示图

在这种情况下,更合适的情节是省略hue并直接使用该类x

g = sns.catplot(x='class',
                palette='Blues',
                data=df,
                kind='count')
plt.show()

没有色调的情节

PS:要获得与第一个情节相似的图例,可以使用 xticks 和 xlabel。请注意,seaborncatplot旨在创建完整的子图网格。g.axes[0][0]抓取ax第一个子图的。

plt.legend(g.axes[0][0].patches,
           [l.get_text() for l in g.axes[0][0].get_xticklabels()],
           title= g.axes[0][0].get_xlabel())
g.axes[0][0].set_xticks([])  # remove the xticks (now in legend)
g.axes[0][0].set_xlabel('')  # remove the xlabel (now title of legend)

推荐阅读