不知何故,为圆圈指定颜色与散点图中的颜色分配不同:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(6,6)) # give plots a rectangular frame
N = 4
r = 0.1
pos = 2.*np.random.rand(N,2) -1
# give different points different color
col = 1./N*np.arange(0,N)
# Method 1
for i,j,k in zip(pos[:,0],pos[:,1],col):
circle = plt.Circle((i,j), r, color = k)
fig.gca().add_artist(circle)
plt.show()
# Method 2
plt.scatter(pos[:,0],pos[:,1], c = col)
plt.show()
为什么方法2工作,而方法1给出以下错误:
ValueError: to_rgba: Invalid rgba arg "0.0"
to_rgb: Invalid rgb arg "0.0"
cannot convert argument to rgb sequence
答案 0 :(得分:5)
您获得的错误是因为您需要直接使用浮动的字符串表示形式而不是浮点值,例如:
circle = plt.Circle((i,j), r, color=`k`) # or str(k)
请注意,在上面我使用了向后刻度,这是str(k)
的简写,它将浮点数转换为字符串,如str(.75) = "0.75"
,并为每个k
提供不同的颜色}值。
以下是错误所指的docs on to_rgba
。
修改强>
在matplotlib中指定颜色的方法有很多种。在上面,您通过float的字符串表示设置引用colormap的float。然后可以通过PolyCollection设置颜色图。
在您的情况下,要使用Circle
更像scatter
,最简单的方法就是直接设置颜色,这可以使用rgba
元组来完成,例如,可以从色图中查找一个。
以下是针对不同y
范围使用三种不同色彩映射的示例。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as clrs
import matplotlib
N, r = 200, .1
cms = matplotlib.cm
maps = [cms.jet, cms.gray, cms.autumn]
fig = plt.figure(figsize=(6,6)) # give plots a rectangular frame
ax = fig.add_subplot(111)
pos = 2.999*np.random.rand(N,2)
for x, y in pos:
cmi = int(y) # an index for which map to use based on y-value
#fc = np.random.random() # use this for random colors selected from regional map
fc = x/3. # use this for x-based colors
color = maps[cmi](fc) # get the right map, and get the color from the map
# ie, this is like, eg, color=cm.jet(.75) or color=(1.0, 0.58, 0.0, 1.0)
circle = plt.Circle((x,y), r, color=color) # create the circle with the color
ax.add_artist(circle)
ax.set_xlim(0, 3)
ax.set_ylim(0, 3)
plt.show()
在上面我做了每个乐队的颜色随x
而变化,因为我觉得它看起来不错,但当然你也可以做随机颜色。只需切换正在使用的fc
行:
答案 1 :(得分:1)
为了使用matplot lib的预定颜色,您应该将字符串传递给颜色字段。在这种情况下,' k'将是黑色而不是简单的k。
此代码没有给我错误:
for i,j,k in zip(pos[:,0],pos[:,1],col):
circle = plt.Circle((i,j), r, color = 'k')
fig.gca().add_artist(circle)
plt.show()
请确保在下一个问题中提供可运行的代码。在这种情况下,变量 N 和 r 未定义。