sns.catplot,缩小条形之间的间隙

时间:2020-04-22 12:24:14

标签: python matplotlib seaborn legend

这是我运行此代码时得到的图 有什么办法可以减少这两根杆之间的间隙,但又不能彼此完全接触?

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

enter image description here

1 个答案:

答案 0 :(得分:1)

问题似乎是列'case'和'class'包含相同的信息,只是名称不同。大小写为1的任何地方,类都是负的,反之亦然。

如果您同时使用xhue,则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()

demo plot

在那种情况下,更合适的情节是省去hue并将类直接用作x

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

plot without hue

PS:要获得与第一个情节相似的图例,可以使用xticks和xlabel。请注意,catplot是用于创建完整的子图网格的。 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)