使用直方图的Matplotlib / Pandas错误


73

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

这是我的一些代码(特别是我要对其进行直方图绘制的熊猫系列对象):

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.

嗯,对我有用。你能显示你的数据框吗?
Andrey Shokhin

嗯,很奇怪,当我这样做时,我实际上可以产生一个直方图:s = dfj2_MARKET1 ['VSPD1_perc'] s.hist()
jonas

是的,但是您使用的是pandashist函数,而不是matplotlibs。这可以按预期处理例如NaN。查看我的更新。
joris

Answers:


127

当系列中有NaN值时,就会发生此错误。可能是这样吗?

histmatplotlib的功能无法很好地处理这些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 larger than min in range parameter.一种选择是例如在绘图前去除NaN。这将起作用:

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

另一种选择是使用大熊猫hist在你的一系列方法和提供axes[0]ax关键字:

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

3

该错误是由于NaN上述值所致。只需使用:

df = df['column_name'].apply(pd.to_numeric)

如果该值不是数字,则应用:

df = df['column_name'].replace(np.nan, your_value)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.