首页 > 解决方案 > 为什么我总是收到此错误:`ValueError: The truth value of an array... Use a.any() or a.all()`,我该如何解决?

问题描述

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

在此处输入图像描述

标签: pythonpython-3.xmatplotlibseabornsubplot

解决方案


我不确定它是否已修复,但您可以提及绘图的特定颜色,如下所示

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

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


推荐阅读