英文:
Why is there a ValueError if all input columns are the same size (22,1) for errorbar matplotlib plot?
问题
我尝试在散点图上添加基于包含标准偏差的数据帧列的误差栏。 x 值是研究中的受试者,y 值是相关的 ITA 值。但是,当我尝试运行代码时,出现了值错误,但是当我检查每个必要列的形状时,发现它们都相同。不确定错误在指示什么。任何帮助都将不胜感激!我的代码/输出如下:
输入:
x1=df_pre_means_ITA[['subj', '']]
y1=df_pre_means_ITA[['subsite_1_ITA', 'mean_values']]
yerr1=df_pre_std_ITA[['subsite_1_ITA', 'std_values']]
print(x1.shape, y1.shape, yerr1.shape)
输出:
(22, 1) (22, 1) (22, 1)
输入:
plt.figure("Subsite 1 Mean ITA Values by Subject")
plt.errorbar(x=x1, y=y1, yerr=yerr1, fmt='o', linewidth=2, capsize=6)
plt.show()
输出:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[293], line 2
1 plt.figure("Subsite 1 Mean ITA Values by Subject")
----> 2 plt.errorbar(x=x1, y=y1, yerr=yerr1, fmt='o', linewidth=2, capsize=6)
3 # ax.errorbar(x=x1, y=y1, yerr=yerr1, fmt='o',linewidth=2,capsize=6)
4 plt.show()
File ~\AppData\Local\anaconda3\Lib\site-packages\matplotlib\pyplot.py:2564, in errorbar(x, y, yerr, xerr, fmt, ecolor, elinewidth, capsize, barsabove, lolims, uplims, xlolims, xuplims, errorevery, capthick, data, **kwargs)
2558 @_copy_docstring_and_deprecators(Axes.errorbar)
2559 def errorbar(
2560 x, y, yerr=None, xerr=None, fmt='', ecolor=None,
2561 elinewidth=None, capsize=None, barsabove=False, lolims=False,
2562 uplims=False, xlolims=False, xuplims=False, errorevery=1,
2563 capthick=None, *, data=None, **kwargs):
-> 2564 return gca().errorbar(
2565 x, y, yerr=yerr, xerr=xerr, fmt=fmt, ecolor=ecolor,
2566 elinewidth=elinewidth, capsize=capsize, barsabove=barsabove,
2567 lolims=lolims, uplims=uplims, xlolims=xlolims,
2568 xuplims=xuplims, errorevery=errorevery, capthick=capthick,
2569 **({"data": data} if data is not None else {}), **kwargs)
File ~\AppData\Local\anaconda3\Lib\site-packages\matplotlib\__init__.py:1442, in _preprocess_data.<locals>.inner(ax, data, *args, **kwargs)
1439 @functools.wraps(func)
1440 def inner(ax, *args, data=None, **kwargs):
1441 if data is None:
-> 1442 return func(ax, *map(sanitize_sequence, args), **kwargs)
1444 bound = new_sig.bind(ax, *args, **kwargs)
1445 auto_label = (bound.arguments.get(label_namer)
1446 or bound.kwargs.get(label_namer))
File ~\AppData\Local\anaconda3\Lib\site-packages\matplotlib\axes\_axes.py:3635, in Axes.errorbar(self, x, y, yerr, xerr, fmt, ecolor, elinewidth, capsize, barsabove, lolims, uplims, xlolims, xuplims, errorevery, capthick, **kwargs)
3633 np.broadcast_to(err, (2, len(dep)))
3634 except ValueError:
-> 3635 raise ValueError(
3636 f"'{dep_axis}err' (shape: {np.shape(err)}) must be a "
3637 f"scalar or a 1D or (2, n) array-like whose shape matches "
3638 f"'{dep_axis}' (shape: {np.shape(dep)})") from None
3639 res = np.zeros(err.shape, dtype=bool) # Default in case of nan
3640 if np.any(np.less(err, -err, out=res, where=(err == err))):
3641 # like err<0, but also works for timedelta and nan.
ValueError: 'yerr' (shape: (22, 1)) must be a scalar or a 1D or (2, n) array-like whose shape matches 'y' (shape: (22, 1))
我已经尝试检查每列的形状,发现它们都是相同的(22,1)形状的数组。所呈现的值错误表明它认为我正在输入不同大小的数组。不确定如何继续处理。
英文:
I am trying to include error bars on a scatter plot based off a column from a dataframe that contains standard deviations. The x values are subjects from a study and the y values are associated ITA values. I'm getting a value error when I try to run the code, however, when I check the shapes of each necessary column I find that they are the same. Unsure what the error is suggesting. Any help would be appreciated! My code/output is listed below:
Input:
x1=df_pre_means_ITA[[('subj', '')]]
y1=df_pre_means_ITA[[('subsite_1_ITA', 'mean_values')]]
yerr1=df_pre_std_ITA[[('subsite_1_ITA', 'std_values')]]
print(x1.shape,y1.shape,yerr1.shape)
Output:
(22, 1) (22, 1) (22, 1)
Input:
plt.figure("Subsite 1 Mean ITA Values by Subject")
plt.errorbar(x=x1, y=y1, yerr=yerr1, fmt='o',linewidth=2,capsize=6)
plt.show()
Output:
ValueError Traceback (most recent call last)
Cell In[293], line 2
1 plt.figure("Subsite 1 Mean ITA Values by Subject")
----> 2 plt.errorbar(x=x1, y=y1, yerr=yerr1, fmt='o',linewidth=2,capsize=6)
3 # ax.errorbar(x=x1, y=y1, yerr=yerr1, fmt='o',linewidth=2,capsize=6)
4 plt.show()
File ~\AppData\Local\anaconda3\Lib\site-packages\matplotlib\pyplot.py:2564, in errorbar(x, y, yerr, xerr, fmt, ecolor, elinewidth, capsize, barsabove, lolims, uplims, xlolims, xuplims, errorevery, capthick, data, **kwargs)
2558 @_copy_docstring_and_deprecators(Axes.errorbar)
2559 def errorbar(
2560 x, y, yerr=None, xerr=None, fmt='', ecolor=None,
2561 elinewidth=None, capsize=None, barsabove=False, lolims=False,
2562 uplims=False, xlolims=False, xuplims=False, errorevery=1,
2563 capthick=None, *, data=None, **kwargs):
-> 2564 return gca().errorbar(
2565 x, y, yerr=yerr, xerr=xerr, fmt=fmt, ecolor=ecolor,
2566 elinewidth=elinewidth, capsize=capsize, barsabove=barsabove,
2567 lolims=lolims, uplims=uplims, xlolims=xlolims,
2568 xuplims=xuplims, errorevery=errorevery, capthick=capthick,
2569 **({"data": data} if data is not None else {}), **kwargs)
File ~\AppData\Local\anaconda3\Lib\site-packages\matplotlib\__init__.py:1442, in _preprocess_data.<locals>.inner(ax, data, *args, **kwargs)
1439 @functools.wraps(func)
1440 def inner(ax, *args, data=None, **kwargs):
1441 if data is None:
-> 1442 return func(ax, *map(sanitize_sequence, args), **kwargs)
1444 bound = new_sig.bind(ax, *args, **kwargs)
1445 auto_label = (bound.arguments.get(label_namer)
1446 or bound.kwargs.get(label_namer))
File ~\AppData\Local\anaconda3\Lib\site-packages\matplotlib\axes\_axes.py:3635, in Axes.errorbar(self, x, y, yerr, xerr, fmt, ecolor, elinewidth, capsize, barsabove, lolims, uplims, xlolims, xuplims, errorevery, capthick, **kwargs)
3633 np.broadcast_to(err, (2, len(dep)))
3634 except ValueError:
-> 3635 raise ValueError(
3636 f"'{dep_axis}err' (shape: {np.shape(err)}) must be a "
3637 f"scalar or a 1D or (2, n) array-like whose shape matches "
3638 f"'{dep_axis}' (shape: {np.shape(dep)})") from None
3639 res = np.zeros(err.shape, dtype=bool) # Default in case of nan
3640 if np.any(np.less(err, -err, out=res, where=(err == err))):
3641 # like err<0, but also works for timedelta and nan.
ValueError: 'yerr' (shape: (22, 1)) must be a scalar or a 1D or (2, n) array-like whose shape matches 'y' (shape: (22, 1))
I have tried checking the shapes of each column and found that they are the same (22,1) shaped array. The value error presented suggests that it thinks I'm inputting different sized arrays. Not sure how to proceed.
答案1
得分: 0
errorbar
参数也可以接受一个2D数组的上下值,这是一个形状为(2, N)的数组;请参阅文档。当使用形状为(1, 22)的2D数组时,Matplotlib可能会对您的意图感到困惑。
在您的情况下,可以使用Numpy的squeeze函数来移除冗余的维度:
import numpy as np
import matplotlib.pyplot as plt
plt.errorbar(x=np.squeeze(x1), y=np.squeeze(y1), yerr=np.squeeze(yerr1), fmt='o', linewidth=2, capsize=6)
现在所有的数组都只是一维的,不会有混淆。
如果您需要经常进行这种压缩操作,当然可以更改变量本身:
x1 = np.squeeze(x1)
(或者如果您后面需要x1
的(1, 22)形式,可以选择一个新的变量名)。
英文:
The errorbar
parameter might also take a 2D array of upper and lower values, which is then an array of (2, N); see the documentation. With a 2D array of size (1, 22), Matplotlib gets confused about your intention.
In your case, use Numpy's squeeze function to remove the redundant dimension:
import numpy as np
import matplotlib.pyplot as plt
plt.errorbar(x=np.squeeze(x1), y=np.squeeze(y1), yerr=np.squeeze(yerr1), fmt='o',linewidth=2,capsize=6)
Now all arrays are simply one-dimensional, and there is no confusion.
If you have to do this squeezing more often, you should of course change the variable itself:
x1 = np.squeeze(x1)
(or a new variable name if you need x1
in its (1, 22) form later.)
答案2
得分: 0
你似乎有3个二维数组,第二维度是平凡的,例如 [[1, 2, 3]]
(这里 shape
是 (3, 1)
)。错误信息所说的是函数需要一个一维数组,例如 [1, 2, 3]
(形状为 (3,)
)。
你可以通过以下方式获得 yerr1
,以获得一维形状的向量(只需使用1对方括号,而不是2):yerr1 = df_pre_std_ITA[('subsite_1_ITA', 'std_values')]
。
英文:
You seem to have 3 2-dimentional arrays with trivial second dimention, ex. [[1, 2, 3]]
(here shape
is (3, 1)
). What the error text says - that the function demands 1d array, ex. [1, 2, 3]
(shape (3, )
).
You can get yerr1
as yerr1 = df_pre_std_ITA[('subsite_1_ITA', 'std_values')]
to get 1d shaped vectors (1 pair of square brackets, not 2).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论