safetyduck
safetyduck

Reputation: 6874

set rgba color of points in matplotlib

According to the docs this is supposed to work. It does not. I must be misreading the docs. Anybody have the fix?

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

Error in 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]

Error in plain 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]

Docs:

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``.

Upvotes: 7

Views: 19727

Answers (2)

John Lyon
John Lyon

Reputation: 11440

Your call to rand (numpy.random.rand) returns a numpy ndarray:

numpy.random.rand(d0, d1, ..., dn) Random values in a given shape.

Create an array of the given shape and propagate it with random samples from a uniform distribution over [0, 1).

Parameters :
d0, d1, ..., dn : int, optional

The dimensions of the returned array, should all be positive. If no argument is given a single Python float is returned.

Returns :
out : ndarray, shape (d0, d1, ..., dn)

Random values.

The matplotlib color argument needs to adhere to one of the formats listed. Specifically, you want to pass an RGBA python tuple.

Try something more like this:

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

Upvotes: 5

Joe Kington
Joe Kington

Reputation: 284890

From your description, it sounds like you want points with multiple different colors?

If so, use scatter, rather than plot. (That's basically the difference between the two. plot is more efficient, but limited to one size/color for all points.)

For example:

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()

Upvotes: 14

Related Questions