在matplotlib中设置rgba点的颜色

时间:2014-09-15 22:27:55

标签: python matplotlib

根据文档,这应该有效。它不是。我一定是在误读文档。有人有修复吗?

from pylab import *
N = 100
x = randn(N)
y = randn(N)
c = rand(N, 4)
plot(x, y, 'o', c=c)

IPython notebook(python3)中的错误:

lib/python3.3/site-packages/IPython/core/formatters.py:239: FormatterWarning: Exception in image/png formatter: to_rgba: Invalid rgba arg "[[ 0.29844256  0.96853857  0.75812229  0.22794978]
 [ 0.81606887  0.31641358  0.53254456  0.44198844]
 [ 0.06961026  0.3265891   0.03006253  0.00485412]
 [ 0.32580911  0.86645991  0.04140443  0.35550554]

普通IPython(python3)中的错误:

ValueError: to_rgba: Invalid rgba arg "[[ -2.78401664e-01  -8.33924015e-01   7.54508871e-01]
 [ -3.02839674e-01  -1.18292516e+00  -7.71274654e-01]
 [ -3.58099013e-01  -1.18899472e+00   1.39868995e+00]

文档:

help(plot)

....

In addition, you can specify colors in many weird and
wonderful ways, including full names (``'green'``), hex
strings (``'#008000'``), RGB or RGBA tuples (``(0,1,0,1)``) or
grayscale intensities as a string (``'0.8'``).  Of these, the
string specifications can be used in place of a ``fmt`` group,
but the tuple forms can be used only as ``kwargs``.

2 个答案:

答案 0 :(得分:11)

根据你的描述,听起来你想要多种不同颜色的点?

如果是,请使用scatter,而不是绘图。 (这基本上是两者之间的差异。plot效率更高,但限制为所有点的一个尺寸/颜色。)

例如:

import matplotlib.pyplot as plt
import numpy as np

N = 100
x = np.random.normal(0, 1, N)
y = np.random.normal(0, 1, N)
c = np.random.random((N, 4))

plt.scatter(x, y, c=c)
plt.show()

答案 1 :(得分:3)

您对randnumpy.random.rand)的调用会返回一个numpy ndarray:

  

numpy.random.rand(d0,d1,...,dn)   给定形状的随机值。

     

创建一个给定形状的数组,并使用来自均匀分布的随机样本在[0,1]上传播它。

     

参数:
  d0,d1,...,dn:int,optional

     

返回数组的维度应该都是正数。如果没有给出参数,则返回一个Python float。

     

退货:
   out:ndarray,shape(d0,d1,...,dn)

     

随机值。

matplotlib color参数需要遵循列出的格式之一。具体来说,你想传递一个RGBA python元组。

尝试更像这样的事情:

color = tuple(numpy.random.rand(4)) # 4 random vals between 0.0-1.0
相关问题