Почему я всегда получаю эту ошибку: `ValueError: Истинное значение массива ... Используйте a.any () или a.all ()` и как мне это исправить? - PullRequest
0 голосов
/ 12 апреля 2020

Я продолжаю сталкиваться с этой ошибкой ValueError: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() при создании графиков с использованием пакета proplot и аналогичным образом пытаюсь воспроизвести графики с использованием matplotlib, который должен работать.

Например, когда я пытаюсь воспроизвести цифру в этой проблеме , я сталкиваюсь с ошибкой. Но проблема закрыта, поэтому я чувствую, что эти графики должны работать.

import pandas as pd
import xarray as xr
import numpy as np
import seaborn as sns
import proplot as plot
import calendar

def drop_nans_and_flatten(dataArray: xr.DataArray) -> np.ndarray:
    """flatten the array and drop nans from that array. Useful for plotting histograms.

    Arguments:
    ---------
    : dataArray (xr.DataArray)
        the DataArray of your value you want to flatten
    """
    # drop NaNs and flatten
    return dataArray.values[~np.isnan(dataArray.values)]


# create dimensions of xarray object
times = pd.date_range(start='1981-01-31', end='2019-04-30', freq='M')
lat = np.linspace(0, 1, 224)
lon = np.linspace(0, 1, 176)

rand_arr = np.random.randn(len(times), len(lat), len(lon))

# create xr.Dataset
coords = {'time': times, 'lat':lat, 'lon':lon}
dims = ['time', 'lat', 'lon']
ds = xr.Dataset({'precip': (dims, rand_arr)}, coords=coords)
ds['month'], ds['year'] = ds['time.month'], ds['time.year']

f, axs = plot.subplots(nrows=4, ncols=3, axwidth=1.5, figsize=(8,12), share=2) # share=3, span=1,
axs.format(
    xlabel='Precip', ylabel='Density', suptitle='Distribution', 
)

month_abbrs = list(calendar.month_abbr)
mean_ds = ds.groupby('time.month').mean(dim='time')
flattened = []
for mth in np.arange(1, 13):
    ax = axs[mth - 1]
    ax.set_title(month_abbrs[mth])
    print(f"Plotting {month_abbrs[mth]}")
    flat = drop_nans_and_flatten(mean_ds.sel(month=mth).precip)
    flattened.append(flat)
    sns.distplot(flat, ax=ax, **{'kde': False})

Это ошибка и вывод:

Plotting Jan
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-3-877b47c30863> in <module>
     45     flat = drop_nans_and_flatten(mean_ds.sel(month=mth).precip)
     46     flattened.append(flat)
---> 47     sns.distplot(flat, ax=ax, **{'kde': False})

/opt/anaconda3/envs/maize-Toff/lib/python3.8/site-packages/seaborn/distributions.py in distplot(a, bins, hist, kde, rug, fit, hist_kws, kde_kws, rug_kws, fit_kws, color, vertical, norm_hist, axlabel, label, ax)
    226         ax.hist(a, bins, orientation=orientation,
    227                 color=hist_color, **hist_kws)
--> 228         if hist_color != color:
    229             hist_kws["color"] = hist_color
    230 

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Используемая версия proplot: 0.5.0

Что я пробовал . Считывание вывода ошибки значения кажется, что формат данных для того, что выводится на экран, является неправильным, но когда я пытаюсь добавить .any () или .all () к переменным deg или flat, это все равно не работает.

enter image description here

1 Ответ

1 голос
/ 12 апреля 2020

Я не уверен, является ли он фиксированным или нет, но вы можете указать конкретный c цвет для графика, как показано ниже

sns.distplot(flat, ax=ax, color = 'r', kde = False)

, чтобы избавиться от ошибки. «color = None» (аргумент по умолчанию), похоже, выдает ошибку.

...