您得到的错误是因为您需要使用float的字符串表示,而不是直接使用float值,例如:circle = plt.Circle((i,j), r, color=`k`) # or str(k)
注意在上面我使用的是倒勾号,是str(k)的简写,它将浮点转换成字符串,比如str(.75) = "0.75",并为每个k值提供不同的颜色。
编辑:
在matplotlib中有许多方法可以指定颜色。在上面,您可以设置通过float的字符串表示来引用colormap的float。然后可以通过一个PolyCollection设置这个的colormap。
在您的例子中,要使用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行: