Python 为单元素序列生成直方图时的Seaborn距离图错误

Python 为单元素序列生成直方图时的Seaborn距离图错误,python,plot,seaborn,Python,Plot,Seaborn,当我使用seaborn(在0.7.1中)可视化直方图时,如果输入序列只包含一个元素,我会得到一个错误。换句话说,类似于 import numpy as np import seaborn as sns num_elements = 1000 sns.distplot(np.random.normal(10, 1, num_elements)) 工作得很好,但是如果我将num_elements设置为1,则会出现以下错误: In [8]: num_elements = 1 In [9]: sn

当我使用seaborn(在0.7.1中)可视化直方图时,如果输入序列只包含一个元素,我会得到一个错误。换句话说,类似于

import numpy as np
import seaborn as sns

num_elements = 1000
sns.distplot(np.random.normal(10, 1, num_elements))
工作得很好,但是如果我将
num_elements
设置为1,则会出现以下错误:

In [8]: num_elements = 1

In [9]: sns.distplot(np.random.normal(10, 1, num_elements))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-35e3f8293582> in <module>()
----> 1 sns.distplot(np.random.normal(10, 1, num_elements))

/usr/local/lib/python2.7/site-packages/seaborn/distributions.pyc in distplot(a, bins, hist, kde, rug, fit, hist_kws, kde_kws, rug_kws, fit_kws, color, vertical, norm_hist, axlabel, label, ax)
    207     if hist:
    208         if bins is None:
--> 209             bins = min(_freedman_diaconis_bins(a), 50)
    210         hist_kws.setdefault("alpha", 0.4)
    211         hist_kws.setdefault("normed", norm_hist)

/usr/local/lib/python2.7/site-packages/seaborn/distributions.pyc in _freedman_diaconis_bins(a)
     28     # From http://stats.stackexchange.com/questions/798/
     29     a = np.asarray(a)
---> 30     h = 2 * iqr(a) / (len(a) ** (1 / 3))
     31     # fall back to sqrt(a) bins if iqr is 0
     32     if h == 0:

TypeError: len() of unsized object
[8]中的
:num_元素=1
[9]中:sns.distplot(np.random.normal(10,1,num_元素))
---------------------------------------------------------------------------
TypeError回溯(最近一次调用上次)
在()
---->1 sns.distplot(np.随机.正常(10,1,num_元素))
/distplot中的usr/local/lib/python2.7/site-packages/seaborn/distributions.pyc(a、bin、hist、kde、rug、fit、hist、kde、rug、rug、fit、color、vertical、norm、axlabel、label、ax)
207如果历史记录:
208如果箱子没有:
-->209个料仓=最小值(\u freedman\u diaconis\u料仓(a),50)
210历史值设置默认值(“alpha”,0.4)
211 hist_kws.setdefault(“normed”,norm_hist)
/usr/local/lib/python2.7/site-packages/seaborn/distributions.pyc in_freedman_diaconis_bins(a)
28#从http://stats.stackexchange.com/questions/798/
29 a=np.asarray(a)
--->30小时=2*iqr(a)/(透镜(a)**(1/3))
31#如果iqr为0,则返回sqrt(a)箱
32如果h==0:
TypeError:未调整大小的对象的len()
在对源代码进行了一番探索之后,我发现可以通过指定存储箱的数量来避免这个错误。但这让我打开了通往另一个世界的大门:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-10-6e6569de737a> in <module>()
----> 1 sns.distplot(np.random.normal(10, 1, num_elements), bins=10)

/usr/local/lib/python2.7/site-packages/seaborn/distributions.pyc in distplot(a, bins, hist, kde, rug, fit, hist_kws, kde_kws, rug_kws, fit_kws, c\olor, vertical, norm_hist, axlabel, label, ax)
    213         hist_color = hist_kws.pop("color", color)
    214         ax.hist(a, bins, orientation=orientation,
--> 215                 color=hist_color, **hist_kws)
    216         if hist_color != color:
    217             hist_kws["color"] = hist_color

/usr/local/lib/python2.7/site-packages/matplotlib/__init__.pyc in inner(ax, *args, **kwargs)
   1817                     warnings.warn(msg % (label_namer, func.__name__),
   1818                                   RuntimeWarning, stacklevel=2)
-> 1819             return func(ax, *args, **kwargs)
   1820         pre_doc = inner.__doc__
   1821         if pre_doc is None:

/usr/local/lib/python2.7/site-packages/matplotlib/axes/_axes.pyc in hist(self, x, bins, range, normed, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, **kwargs)
   5933             x = np.array([[]])
   5934         else:
-> 5935             x = _normalize_input(x, 'x')
   5936         nx = len(x)  # number of datasets
   5937

/usr/local/lib/python2.7/site-packages/matplotlib/axes/_axes.pyc in _normalize_input(inp, ename)
   5875                 else:
   5876                     raise ValueError(
-> 5877                         "{ename} must be 1D or 2D".format(ename=ename))
   5878                 if inp.shape[1] < inp.shape[0]:
   5879                     warnings.warn(

ValueError: x must be 1D or 2D
---------------------------------------------------------------------------
ValueError回溯(最近一次调用上次)
在()
---->1 sns.distplot(np.random.normal(10,1,num_元素),bin=10)
/distplot中的usr/local/lib/python2.7/site-packages/seaborn/distributions.pyc(a、bin、hist、kde、rug、fit、hist_-kws、kde_-kws、rug_-kws、fit_-kws、c\olor、vertical、norm_-hist、axlabel、label、ax)
213 hist_color=hist_kws.pop(“颜色”,颜色)
214 ax.hist(a,箱子,方向=方向,
-->215颜色=历史颜色,**历史颜色(kws)
216如果历史颜色!=颜色:
217历史颜色kws[“颜色”]=历史颜色
/usr/local/lib/python2.7/site packages/matplotlib/________.pyc在内部(ax,*args,**kwargs)
1817警告。警告(消息%(标签名称,功能名称),
1818运行时警告,堆栈级别=2)
->1819返回函数(ax,*args,**kwargs)
1820预存单据=内部单据__
1821如果pre_doc为无:
/usr/local/lib/python2.7/site-packages/matplotlib/axes//u axes.pyc(self、x、bins、range、normed、weights、cumulative、bottom、histtype、align、orientation、rwidth、log、color、label、stacked、**kwargs)
5933 x=np.array([]]
5934其他:
->5935 x=_规范化_输入(x,'x')
5936 nx=len(x)#数据集数量
5937
/usr/local/lib/python2.7/site-packages/matplotlib/axes//u axes.pyc in\u normalize\u输入(inp,ename)
5875其他:
5876上升值错误(
->5877“{ename}必须是1D或2D”。格式(ename=ename))
5878如果输入形状[1]<输入形状[0]:
5879警告。警告(
ValueError:x必须是1D或2D

这是怎么回事?有什么办法可以让我强迫seaborn为这个单一元素系列绘制直方图吗?在上下文中,我需要这个,因为我在一个共享轴上绘制多个直方图,描述不同的条件。在某些情况下,在这种情况下可能只有一个元素,但我应该能够绘制只有一个条!

当数组长度为1时,您可以通过复制以下值来欺骗seaborn:

rs = np.random.RandomState(0)
num_elements = 1
x = rs.normal(10, 1, num_elements)
sns.distplot(np.r_[x, x], kde=False, norm_hist=True)

或者,如果您不需要seaborn提供的产品(大多数产品对单个元素没有意义),只需使用matplotlib或pandas:

plt.hist(x, bins=1)


< /P>我认为<代码>数组([10.37823942)] < /代码>是一个单元素序列。此外,<代码> tMP= nP.No.Calm(10, 1, 1);断言TMP是NP。运行无误,表明

np.至少返回同一个对象。另外,关于numpy中的标量主题,请注意
tmp
具有
形状
(1,)
1
len
。我可以用
np.asscalar
转换成一个真正的标量,以证明numpy有这种区别,它不再具有形状或长度。是的,你说得对。很好的解决方法。不幸的是,这意味着我必须规范化,或者接受双倍的计数。一个在我的系统中有效的相关解决方法案例涉及限制条形范围(例如,
条形=范围(0,最大值,最小尺寸)
)然后在数据集中添加一个元素,比如说
max_value+1
。不过,我仍然希望找到一个直接的解决方案。请注意,我在循环中多次调用
distplot
,在同一轴上绘制一组覆盖各种条件的重叠直方图。我在这些图中使用了seaborn的功能,但需要修改能够绘制单个元素系列,因为在某些图中,其中一个条件只有一个元素。此外,此用例排除了标准化。如果您没有绘制KDE(因此没有使用标准化)并指定仓位大小(因此没有使用参考规则默认值)然后,
sns.distplot
ax.hist
@Ohrounuruus之间就没有功能上的区别了。我不明白这个问题。你发布了一些不起作用的代码。如果它起作用,我希望它能创建一个像我的第一个一样的图(模样式).我不知道这不是你期望的。请澄清。其他两种选择可能对你有效,也可能对你无效,这取决于你的实际需要。根据你提供的信息,这是我所知的
pd.Series(x).hist(bins=1);