I am trying to set the colors on a scatter plot using meshgrid input data. The code I am using is the following one :
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()
Executing this code returns the following error :
could not convert string to float: 'b'
While if I chane the color map to float values :
col = np.where(zv<0.5,0.1,0.2)
This works without any issue. Any idea why ?
When looking at the part of the code throwing the error, I see the following remarks :
# tuple color.
# Python 2.7 / numpy 1.6 apparently require this to return builtin floats,
# not numpy floats.
try:
c = tuple(map(float, c))
Maybe there is something to understand there to find the solution but I could not get it
From the scatter
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.
So the array given to c
must either be a 1D array or a 2D array of RGB or RGBA values. It cannot be an arbitrary 2D array.
Hence you need to flatten your array,
col = np.where(zv<0.5,'b','r').flatten()
plt.scatter(xv,yv,c=col)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.