【问题标题】:Extending the range of bins in seaborn histogram扩展 seaborn 直方图中的 bin 范围
【发布时间】:2018-04-09 22:08:04
【问题描述】:

我正在尝试使用 seaborn 创建一个直方图,其中箱从 0 开始到 1。但是,只有 0.22 到 0.34 范围内的日期。我想要更多的空白空间以获得视觉效果,以更好地呈现数据。

我用

创建我的工作表
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', sheetname='IvT')

在这里,我为我的列表创建了一个变量,我认为应该定义直方图的 bin 范围。

st = pd.Series(df['Short total'])
a = np.arange(0, 1, 15, dtype=None)

而直方图本身是这样的

sns.set_style("white")
plt.figure(figsize=(12,10))
plt.xlabel('Ration short/total', fontsize=18)
plt.title ('CO3 In vitro transcription, Na+', fontsize=22)

ax = sns.distplot(st, bins=a, kde=False)

plt.savefig("hist.svg", format="svg")
plt.show()

Histogram

它创建了一个图形位,x 的范围从 0 到 0.2050,y 的范围从 -0.04 到 0.04。和我想象的完全不同。我用谷歌搜索了很长一段时间,但似乎找不到我的具体问题的答案。

已经,谢谢你们的帮助。

【问题讨论】:

    标签: python histogram seaborn bins


    【解决方案1】:

    这里有几种方法可以达到预期的效果。例如,您可以在绘制直方图后更改 x 轴范围,或调整创建 bin 的范围。

    import seaborn as sns
    
    # Load sample data and create a column with values in the suitable range
    iris = sns.load_dataset('iris')
    iris['norm_sep_len'] = iris['sepal_length'] / (iris['sepal_length'].max()*2)
    sns.distplot(iris['norm_sep_len'], bins=10, kde=False)
    

    更改 xaxis 限制(仍会在您的数据范围内创建 bin):

    ax = sns.distplot(iris['norm_sep_len'], bins=10, kde=False)
    ax.set_xlim(0,1)
    

    在 0 到 1 的范围内创建 bin:

    sns.distplot(iris['norm_sep_len'], bins=10, kde=False, hist_kws={'range':(0,1)})
    

    由于 bin 的范围更大,如果您想拥有与调整 xlim 时相同的 bin 宽度,您现在需要使用更多的 bin:

    sns.distplot(iris['norm_sep_len'], bins=45, kde=False, hist_kws={'range':(0,1)})
    

    【讨论】:

    • 非常感谢。那成功了。有没有办法,我也可以使用以下参数来获取条形边框? hist_kws=dict(edgecolor="k", linewidth=2)
    • @Jul hist_kws 将参数从 matplotlib 发送到底层直方图函数。您可以通过阅读文档查看可以传递的所有参数:import matplotlib.pyplot as plt; ?plt.hist 在这种情况下,您希望将histtype 指定为'bar'。不要忘记接受并赞成这个答案,它解决了你的问题。
    • 如果我将直方图的代码更改为 ax = sns.distplot(st,bins=34, kde=False, color = '#007b7f', histt​​ype ='bar',hist_kws=dict( edgecolor="k", linewidth=2)) 它给了我一条错误消息: distplot() got an unexpected keyword argument 'histt​​ype' 。还是我必须更改 matplotlib 中的 histt​​ype?
    • 只有hist_kws 字典中的参数“按原样”传递给plt.hist。这应该工作hist_kws={'histtype':'bar'}
    • 其实那个是默认的,不需要设置。我认为线宽可能会改变。我正在调查这个。也许打开一个新问题,因为这是一个不同的话题。随意在此处链接。