Why do I always get this error: `ValueError: The truth value of an array... Use a.any() or a.all()` and how do I fix it?

Why do I always get this error: `ValueError: The truth value of an array... Use a.any() or a.all()` and how do I fix it?

我在使用包 proplot 创建图时一直 运行ning 到这个 ValueError: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 并且同样尝试使用应该工作的 matplotlib 重现图。

例如,当我尝试重现this issue中的图形时,我运行进入了错误。但是这个问题已经解决了,所以我觉得这些情节应该可行。

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() 添加到变量 precip 或 flat 时,它仍然不起作用。

我不确定它是否已修复,但是您可以如下所示提及情节的具体颜色

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

消除错误。 'color = None'(默认参数)似乎给出了错误。