Подтвердить что ты не робот

Ошибка Matplotlib/Pandas с использованием гистограммы

У меня проблема с созданием гистограмм из объектов серии 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 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.
4b9b3361

Ответ 1

Эта ошибка возникает между прочим, когда у вас есть значения NaN в серии. Это может быть так?

Эти NaN плохо обрабатываются функцией hist matplotlib. Например:

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

Другим вариантом является использование метода pandas hist в вашей серии и предоставление axes[0] ключевому слову ax:

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