2013-12-18 74 views
46

我有一个问题,从熊猫系列对象的直方图,我不明白为什么它不起作用。代码之前工作正常,但现在不行。使用直方图Matplotlib /熊猫错误

这里有点我的代码(具体来讲,熊猫系列的对象我想要做的直方图):

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. 
+0

嗯,它为我工作。你可以显示你的数据框? –

+0

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

+0

是的,但是你使用熊猫'hist'函数,而不是matplotlibs。而且这可以像预期的那样处理NaNs。查看我的更新。 – joris

回答

78

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

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

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') 
+0

完美的作品!非常感谢你 – jonas

+0

Perfect NaN创建错误,pandas/pyplot异常不会共享足够的信息。真的很有帮助。 – Doogle

+0

完美的作品! –