python - 使用直方图的 Matplotlib/Pandas 错误

标签 python matplotlib pandas histogram

我在从 pandas 系列对象制作直方图时遇到问题,我不明白为什么它不起作用。该代码之前运行良好,但现在不行。

这是我的一些代码(特别是我正在尝试制作直方图的 Pandas 系列对象):

type(dfj2_MARKET1['VSPD2_perc'])

输出结果: pandas.core.series.Series

这是我的绘图代码:

fig, axes = plt.subplots(1, 7, figsize=(30,4))
axes[0].hist(dfj2_MARKET1['VSPD1_perc'],alpha=0.9, color='blue')
axes[0].grid(True)
axes[0].set_title(MARKET1 + '  5-40 km / h')

错误信息:

    AttributeError                            Traceback (most recent call last)
    <ipython-input-75-3810c361db30> in <module>()
      1 fig, axes = plt.subplots(1, 7, figsize=(30,4))
      2 
    ----> 3 axes[1].hist(dfj2_MARKET1['VSPD2_perc'],alpha=0.9, color='blue')
      4 axes[1].grid(True)
      5 axes[1].set_xlabel('Time spent [%]')

    C:\Python27\lib\site-packages\matplotlib\axes.pyc in hist(self, x, bins, range, normed,          weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label,    stacked, **kwargs)
   8322             # this will automatically overwrite bins,
   8323             # so that each histogram uses the same bins
-> 8324             m, bins = np.histogram(x[i], bins, weights=w[i], **hist_kwargs)
   8325             m = m.astype(float) # causes problems later if it's an int
   8326             if mlast is None:

    C:\Python27\lib\site-packages\numpy\lib\function_base.pyc in histogram(a, bins, range,     normed, weights, density)
    158         if (mn > mx):
    159             raise AttributeError(
--> 160                 'max must be larger than min in range parameter.')
    161 
    162     if not iterable(bins):

AttributeError: max must be larger than min in range parameter.

最佳答案

当您在 Series 中有 NaN 值时,会发生此错误。会这样吗?

matplotlib 的 hist 函数不能很好地处理这些 NaN。例如:

s = pd.Series([1,2,3,2,2,3,5,2,3,2,np.nan])
fig, ax = plt.subplots()
ax.hist(s, alpha=0.9, color='blue')

产生相同的错误 AttributeError: max must be greater than min in range parameter. 一种选择是例如在绘图前删除 NaN。这将起作用:

ax.hist(s.dropna(), alpha=0.9, color='blue')

另一种选择是在您的系列中使用 pandas hist 方法并将 axes[0] 提供给 ax 关键字:

dfj2_MARKET1['VSPD1_perc'].hist(ax=axes[0], alpha=0.9, color='blue')

关于python - 使用直方图的 Matplotlib/Pandas 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20656663/

相关文章:

python - 复合相等性测试在 python 中短路了吗?

python - 如何在多索引 Pandas Dataframe 中按组更新前 N 行的值?

python - Getdist 图未显示在控制台中

python - 对于直方图,如何保留所有指定的 bin-ticks 沿 x 轴并仅显示指定的 bin-ticks 的数字标签?

python - 如何在 numpy python 中创建相似度矩阵?

Python 函数及其 __call__ 属性

python - 如何在不改变绘图的情况下更改 matplotlib 中的图形 Canvas 大小?

python - Pandas 数据框旋转

python - Pandas 数据框过滤

python - 根据特定日期设置 matplotlib 网格刻度