【问题标题】:Increasing space between bins in seaborn distplot在 seaborn distplot 中增加 bin 之间的空间
【发布时间】:2018-04-19 01:48:20
【问题描述】:

所以我有一个可能很简单的问题。我使用 seaborn 从 excel 文件中的数据创建了一个直方图。为了更好的可视化,我想在条/箱之间留一些空间。这可能吗?

我的代码如下所示

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

%matplotlib inline
from IPython.display import set_matplotlib_formats
set_matplotlib_formats('svg', 'pdf')


df = pd.read_excel('test.xlsx')
sns.set_style("white")
#sns.set_style("dark")
plt.figure(figsize=(12,10))
plt.xlabel('a', fontsize=18)
plt.ylabel('test2', fontsize=18)

plt.title ('tests ^2', fontsize=22)


ax = sns.distplot(st,bins=34, kde=False, hist_kws={'range':(0,1), 'edgecolor':'black', 'alpha':1.0}, axlabel='test1')

第二个问题虽然有点离题,但我如何才能真正提升图表标题中的指数?

谢谢!

【问题讨论】:

  • @jojo:感谢您的链接。我希望能得到更直接的东西。否则我必须将图形导出为 svg 并使用 inkscape 等进行更正。
  • 好的,转储问题,我还需要乳胶分配器才能工作吗?

标签: python matplotlib histogram seaborn bins


【解决方案1】:

matplotlib hist 函数有一个参数rwidth

rwidth:标量或无,可选
条形的相对宽度作为 bin 宽度的一部分。

您可以通过hist_kws 参数在distplot 中使用它。

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

x = np.random.normal(0.5,0.2,1600)

ax = sns.distplot(x,bins=34, kde=False, 
                  hist_kws={"rwidth":0.75,'edgecolor':'black', 'alpha':1.0})

plt.show()

【讨论】:

  • 不幸的是,不再适用于 seaborn >= 0.11。 distplot() 变成了displot()histplot(),都没有传递rwidth 参数。
  • 2022:hist_kws 参数可用于sns.distplot(),但不适用于sns.histplot()
【解决方案2】:

对于 Seaborn >= 0.11,使用 shrink 参数。它通过此参数相对于 binwidth 缩放每个条的宽度。其余的将是空白空间。

文档:https://seaborn.pydata.org/generated/seaborn.histplot.html

编辑: OP 最初询问sns.distplot(),但是在当前版本>=0.11 中,它已被弃用,而支持sns.histplotsns.displot()。由于 OP 正在生成直方图,因此 hist 模式下的 histplotdisplot 都将采用 shrink

【讨论】:

  • OP 询问sns.displot(),而sns.histplot() 采用不同的参数。
  • @PatrickT 感谢您的关注,我已经改进了答案。
  • 给我点赞。 :-)
【解决方案3】:

发布我的答案后,我意识到我的回答与所要求的相反。我在试图弄清楚如何删除条之间的空间时发现了这个问题。我几乎删除了我的答案,但万一其他人偶然发现了这个问题并试图删除 seaborn 的 histplot 中的条之间的空间,我将暂时保留它。

感谢@miro Seaborn 的updated documentation,我发现element='step' 对我有用。根据您的具体需求,element='poly' 可能就是您所追求的。

我的“步骤”实现:

fig,axs = plt.subplots(4,2,figsize=(10,10))
i,j = 0,0
for col in cols:
    sns.histplot(df[col],ax=axs[i,j],bins=100,element='step')
    axs[i,j].set(title="",ylabel='Frequency',xlabel=labels[col])
    i+=1
    if i == 4: 
        i = 0
        j+=1

我的“poly”实现:

fig,axs = plt.subplots(4,2,figsize=(10,10))
i,j = 0,0
for col in cols:
    sns.histplot(df[col],ax=axs[i,j],bins=100,element='poly')
    axs[i,j].set(title="",ylabel='Frequency',xlabel=labels[col])
    i+=1
    if i == 4: 
        i = 0
        j+=1

【讨论】:

  • OP 询问的是sns.distplot() 而不是sns.histplot()。事实证明,它们完全不同。
猜你喜欢
  • 2017-10-12
  • 2015-10-22
  • 2020-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多