2014-10-02 81 views
3

不知何故,到圈子指定颜色的散点图工作从指定颜色不同:如何将颜色分配给matplotlib中的圆圈?

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 
+2

我发现使用'c'而不是'color'会使着色的方式变得更好。 – 2015-05-29 14:09:52

回答

5

的错误你得到是因为您需要使用浮点数的字符串表示形式而不是直接使用浮点数值,例如:

circle = plt.Circle((i,j), r, color=`k`) # or str(k) 
circle = plt.Circle((i,j), r, color=`k`) # or str(k) 

在上面的注意我使用反向滴答,str(k),将浮点数转换为字符串,如str(.75) = "0.75",并会给每个k值不同的颜色。

以下是错误引用的docs on to_rgba

编辑:
enter image description here

有很多种方法来指定matplotlib颜色。在上面,通过浮点的字符串表示形式来设置引用颜色映射的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线正在使用:

enter image description here

1

为了使用matplot 11b的预定的颜色,你应该通过字符串的颜色字段。在这种情况下,'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未定义。

+0

谢谢你指出缺少的声明。我加了他们。 您的解决方案适用于灰度色。你知道如何修改'真实'的颜色吗? – user3058865 2014-10-02 18:29:04

+2

tom10给出的答案相当完整。你可以定义你想要的任何颜色,并且还有一些预定义的颜色。你可以在这里找到所有的信息:[link](http://matplotlib.org/api/colors_api。html)你可以使用任何预定义的字符,就像你用'k'黑色一样。 – alasimpara 2014-10-03 19:06:14