不知何故,为圆圈指定颜色与散点图中的颜色分配不同:
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()
Run Code Online (Sandbox Code Playgroud)
为什么方法2工作,而方法1给出以下错误:
ValueError: to_rgba: Invalid rgba arg "0.0"
to_rgb: Invalid rgb arg "0.0"
cannot convert argument to rgb sequence
Run Code Online (Sandbox Code Playgroud)
您得到的错误是因为您需要直接使用float的字符串表示而不是float值,例如:
circle = plt.Circle((i,j), r, color=`k`) # or str(k)
Run Code Online (Sandbox Code Playgroud)
请注意,在上面我使用的是后向刻度,一种简写str(k),将float转换为字符串str(.75) = "0.75",并为每个k值赋予不同的颜色.
以下是错误所指的文档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()
Run Code Online (Sandbox Code Playgroud)
在上面我为每个乐队制作的颜色各不相同,x因为我认为它看起来不错,但当然你也可以做随机颜色.只需切换fc正在使用的线路:

| 归档时间: |
|
| 查看次数: |
7775 次 |
| 最近记录: |