【发布时间】:2017-11-11 19:28:59
【问题描述】:
我正在尝试使用网格输入数据在散点图上设置颜色。 我使用的代码如下:
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()
执行此代码会返回以下错误:
could not convert string to float: 'b'
如果我将颜色图更改为浮点值:
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))
也许那里有一些需要了解的东西才能找到解决方案,但我无法得到它
【问题讨论】:
-
您需要展平颜色数组 (
col = np.where(zv<0.5,'b','r').flatten()))。然后上面的代码产生了like this。为了找出代码不适合您的原因,您需要向minimal reproducible example 提供重现所需的所有信息,例如软件版本等。 -
感谢您的回答。但是为什么我需要对颜色输入进行展平呢?从文档中,我了解 c 可以作为二维数组提供?
标签: python matplotlib