Matplotlib散点图颜色

2024-04-19 01:27:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用网格输入数据设置散点图的颜色。 我使用的代码如下:

xmesh = np.linspace(-5, 5, 30)
ymesh = np.linspace(-5, 5, 30)
xv, yv = np.meshgrid(xmesh, ymesh)
zv = a*xv+b*yv+c #a,b,c are some scalar constants
col = np.where(zv<0.5,'b','r')
plt.scatter(xv,yv,c=col)
plt.show()

执行此代码将返回以下错误:

^{pr2}$

如果将颜色贴图更改为浮点值:

col = np.where(zv<0.5,0.1,0.2) 

这没有任何问题。知道为什么吗?在

在查看引发错误的代码部分时,我看到以下备注:

# tuple color.
# Python 2.7 / numpy 1.6 apparently require this to return builtin floats,
# not numpy floats.
try:
c = tuple(map(float, c))

也许有一些东西需要去理解才能找到解决办法,但我却没能找到


Tags: 代码numpy颜色错误nppltcolwhere
1条回答
网友
1楼 · 发布于 2024-04-19 01:27:57

^{} documentation

c can be a 2-D array in which the rows are RGB or RGBA, however, including the case of a single row to specify the same color for all points.

所以给c的数组必须是一个一维数组,或者是一个包含RGB或RGBA值的2D数组。它不能是任意二维数组。在

所以你需要把你的阵型变平

col = np.where(zv<0.5,'b','r').flatten()
plt.scatter(xv,yv,c=col)

相关问题 更多 >