【问题标题】: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?为什么我总是收到此错误:`ValueError: The truth value of an array... Use a.any() or a.all()`,我该如何解决?
【发布时间】:2020-07-24 14:20:41
【问题描述】:

在使用 proplot 包创建绘图时,我一直遇到这个 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 时,它仍然不起作用。

【问题讨论】:

    标签: python python-3.x matplotlib seaborn subplot


    【解决方案1】:

    我不确定它是否是固定的,但你可以提到如下图的具体颜色

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

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

    【讨论】:

    • 哇,就是这样。无法相信这是一个如此简单的解决方案。谢谢!
    • 很高兴为您提供帮助..您现在可以专注于您的实际研究 :) - 来自前研究生。
    猜你喜欢
    • 2023-02-03
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 2018-07-28
    相关资源
    最近更新 更多