ValueError:绘制散点图时 RGBA 值应在 0-1 范围内

发布于 2025-01-13 12:00:29 字数 3663 浏览 2 评论 0原文

我试图生成一个散点图来显示 PCA 变换之前和之后的数据,类似于 教程

为此,我运行以下代码:

fig, axes = plt.subplots(1,2)
axes[0].scatter(X.iloc[:,0], X.iloc[:,1], c=y)
axes[0].set_xlabel('x1')
axes[0].set_ylabel('x2')
axes[0].set_title('Before PCA')
axes[1].scatter(X_new[:,0], X_new[:,1], c=y)
axes[1].set_xlabel('PC1')
axes[1].set_ylabel('PC2')
axes[1].set_title('After PCA')
plt.show()

这导致出现此错误:

ValueError: RGBA values should be within 0-1 range

X 是预处理的特征矩阵,其中包含 196 个样本和 59 个特征。而 y 是因变量,包含两个类 [0, 1]。

以下是完整的错误消息:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-109-2c4f74ddce3f> in <module>
      1 fig, axes = plt.subplots(1,2)
----> 2 axes[0].scatter(X.iloc[:,0], X.iloc[:,1], c=y)
      3 axes[0].set_xlabel('x1')
      4 axes[0].set_ylabel('x2')
      5 axes[0].set_title('Before PCA')

~/anaconda3/lib/python3.7/site-packages/matplotlib/__init__.py in inner(ax, data, *args, **kwargs)
   1597     def inner(ax, *args, data=None, **kwargs):
   1598         if data is None:
-> 1599             return func(ax, *map(sanitize_sequence, args), **kwargs)
   1600 
   1601         bound = new_sig.bind(ax, *args, **kwargs)

~/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_axes.py in scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, plotnonfinite, **kwargs)
   4495                 offsets=offsets,
   4496                 transOffset=kwargs.pop('transform', self.transData),
-> 4497                 alpha=alpha
   4498                 )
   4499         collection.set_transform(mtransforms.IdentityTransform())

~/anaconda3/lib/python3.7/site-packages/matplotlib/collections.py in __init__(self, paths, sizes, **kwargs)
    881         """
    882 
--> 883         Collection.__init__(self, **kwargs)
    884         self.set_paths(paths)
    885         self.set_sizes(sizes)

~/anaconda3/lib/python3.7/site-packages/matplotlib/collections.py in __init__(self, edgecolors, facecolors, linewidths, linestyles, capstyle, joinstyle, antialiaseds, offsets, transOffset, norm, cmap, pickradius, hatch, urls, offset_position, zorder, **kwargs)
    125 
    126         self._hatch_color = mcolors.to_rgba(mpl.rcParams['hatch.color'])
--> 127         self.set_facecolor(facecolors)
    128         self.set_edgecolor(edgecolors)
    129         self.set_linewidth(linewidths)

~/anaconda3/lib/python3.7/site-packages/matplotlib/collections.py in set_facecolor(self, c)
    676         """
    677         self._original_facecolor = c
--> 678         self._set_facecolor(c)
    679 
    680     def get_facecolor(self):

~/anaconda3/lib/python3.7/site-packages/matplotlib/collections.py in _set_facecolor(self, c)
    659         except AttributeError:
    660             pass
--> 661         self._facecolors = mcolors.to_rgba_array(c, self._alpha)
    662         self.stale = True
    663 

~/anaconda3/lib/python3.7/site-packages/matplotlib/colors.py in to_rgba_array(c, alpha)
    277             result[mask] = 0
    278         if np.any((result < 0) | (result > 1)):
--> 279             raise ValueError("RGBA values should be within 0-1 range")
    280         return result
    281     # Handle single values.

ValueError: RGBA values should be within 0-1 range

我不确定导致此错误的原因,并希望能帮助您解决此问题。谢谢!

I am attempting to generate a scatter plot to show data before and after the PCA transform, similar to this tutorial.

To do this, I am running the following code:

fig, axes = plt.subplots(1,2)
axes[0].scatter(X.iloc[:,0], X.iloc[:,1], c=y)
axes[0].set_xlabel('x1')
axes[0].set_ylabel('x2')
axes[0].set_title('Before PCA')
axes[1].scatter(X_new[:,0], X_new[:,1], c=y)
axes[1].set_xlabel('PC1')
axes[1].set_ylabel('PC2')
axes[1].set_title('After PCA')
plt.show()

Which is causing this error to appear:

ValueError: RGBA values should be within 0-1 range

X is the preprocessed matrix of features, which contains 196 samples and 59 features. Whereas y is the dependent variable and contains two classes [0, 1].

Here is the full error message:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-109-2c4f74ddce3f> in <module>
      1 fig, axes = plt.subplots(1,2)
----> 2 axes[0].scatter(X.iloc[:,0], X.iloc[:,1], c=y)
      3 axes[0].set_xlabel('x1')
      4 axes[0].set_ylabel('x2')
      5 axes[0].set_title('Before PCA')

~/anaconda3/lib/python3.7/site-packages/matplotlib/__init__.py in inner(ax, data, *args, **kwargs)
   1597     def inner(ax, *args, data=None, **kwargs):
   1598         if data is None:
-> 1599             return func(ax, *map(sanitize_sequence, args), **kwargs)
   1600 
   1601         bound = new_sig.bind(ax, *args, **kwargs)

~/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_axes.py in scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, plotnonfinite, **kwargs)
   4495                 offsets=offsets,
   4496                 transOffset=kwargs.pop('transform', self.transData),
-> 4497                 alpha=alpha
   4498                 )
   4499         collection.set_transform(mtransforms.IdentityTransform())

~/anaconda3/lib/python3.7/site-packages/matplotlib/collections.py in __init__(self, paths, sizes, **kwargs)
    881         """
    882 
--> 883         Collection.__init__(self, **kwargs)
    884         self.set_paths(paths)
    885         self.set_sizes(sizes)

~/anaconda3/lib/python3.7/site-packages/matplotlib/collections.py in __init__(self, edgecolors, facecolors, linewidths, linestyles, capstyle, joinstyle, antialiaseds, offsets, transOffset, norm, cmap, pickradius, hatch, urls, offset_position, zorder, **kwargs)
    125 
    126         self._hatch_color = mcolors.to_rgba(mpl.rcParams['hatch.color'])
--> 127         self.set_facecolor(facecolors)
    128         self.set_edgecolor(edgecolors)
    129         self.set_linewidth(linewidths)

~/anaconda3/lib/python3.7/site-packages/matplotlib/collections.py in set_facecolor(self, c)
    676         """
    677         self._original_facecolor = c
--> 678         self._set_facecolor(c)
    679 
    680     def get_facecolor(self):

~/anaconda3/lib/python3.7/site-packages/matplotlib/collections.py in _set_facecolor(self, c)
    659         except AttributeError:
    660             pass
--> 661         self._facecolors = mcolors.to_rgba_array(c, self._alpha)
    662         self.stale = True
    663 

~/anaconda3/lib/python3.7/site-packages/matplotlib/colors.py in to_rgba_array(c, alpha)
    277             result[mask] = 0
    278         if np.any((result < 0) | (result > 1)):
--> 279             raise ValueError("RGBA values should be within 0-1 range")
    280         return result
    281     # Handle single values.

ValueError: RGBA values should be within 0-1 range

I am unsure what is causing this error and would appreciate help in figuring this out. Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

只怪假的太真实 2025-01-20 12:00:29

c= 参数>ax.scatter 可以通过多种方式给出:

  • 使用 cmap 和范数将 n 个数字映射到颜色的标量或序列。所以是一个数字,或者一个类似列表的一维数字序列。
  • 二维数组,其中行为 RGB 或 RGBA。例如,类似 [[1,0,0], [0,0,1]]。所有这些值都必须介于 0 和 1 之间。此外,每个条目应该有 3 个(对于 RGB)或 4 个(对于 RGBA)值。
  • 长度为 n 的颜色序列。例如 ["red", "#B789C0", "turquoise"]
  • 单一颜色格式字符串。例如“cornflowerblue”

现在,当给出一个数字数组时,为了能够区分第一种情况和第二种情况,matplotlib 仅查看数组维度。如果是一维,matplotlib 假设第一种情况。对于 2D,它假设第二种情况。请注意,Nx11xN 数组也被视为二维数组。您可以使用 np.squeeze() 来“挤出”虚拟第二个维度。

The c= parameter of ax.scatter can be given in several ways:

  • A scalar or sequence of n numbers to be mapped to colors using cmap and norm. So a single number, or a list-like 1D sequence of numbers.
  • A 2D array in which the rows are RGB or RGBA. E.g. something like [[1,0,0], [0,0,1]]. All these values need to be between 0 and 1. Moreover, there should be either 3 (for RGB) or 4 (for RGBA) values per entry.
  • A sequence of colors of length n. E.g. ["red", "#B789C0", "turquoise"]
  • A single color format string. E.g. "cornflowerblue".

Now, when an array of numbers is given, to be able to distinguish between the first and the second case, matplotlib just looks at the array dimension. If it is 1D, matplotlib assumes the first case. For 2D, it assumes the second case. Note that also an Nx1 or an 1xN array is considered 2D. You can use np.squeeze() to "squeeze out" the dummy second dimension.

雨的味道风的声音 2025-01-20 12:00:29

在每个 RGB 值周围使用此函数:

def rgb_normalised(rgb_no):
    return (1/256)*rgb_no

示例:

rect1 = matplotlib.patches.Rectangle((-90,-90), 180, 70, fc= 
(rgb_normalised(204),rgb_normalised(255),rgb_normalised(255),0.5), 
ec=(0,0,0,1))

Use this function around each rgb value:

def rgb_normalised(rgb_no):
    return (1/256)*rgb_no

example:

rect1 = matplotlib.patches.Rectangle((-90,-90), 180, 70, fc= 
(rgb_normalised(204),rgb_normalised(255),rgb_normalised(255),0.5), 
ec=(0,0,0,1))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文