Reputation: 4317
I keep running into this ValueError: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
when creating plots using the package proplot
and similarly trying to reproduce plots using matplotlib that should work.
For example, when I try to reproduce the figure in this issue, I run into the error. But the issue is closed, so I feel like these plots should work.
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})
This is the error and the output:
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()
The version of proplot I'm using is: 0.5.0
What I've tried. Reading the value error output it seems like the format of the data for what's being plotted is wrong, but when I try to add .any() or .all() to the variables precip or flat, it still doesn't work.
Upvotes: 0
Views: 750
Reputation: 4199
I am not sure if it is fixed or not, but you can mention the specific color for the plot as shown below
sns.distplot(flat, ax=ax, color = 'r', kde = False)
to get rid of the error. 'color = None' (default argument) seems to be giving the error.
Upvotes: 1