user2497586
user2497586

Reputation:

Assign random color to matplotlib graph

I am trying to plot some polygons in matplotlib, and I've been able to use pre-defined HTML colors, but I would like to use random RGB tuples. However, I can't figure it out.

Here's the code I've been trying:

>>> import matplotlib
>>> matplotlib.use('agg')
>>> import matplotlib.pyplot as plt
>>> import random
>>> fig, ax = plt.subplots()
>>> ax.plot([1,2,3], [4,5,6], (.4, .5, .6))

And I get this error: raise ValueError('third arg must be a format string')

What I would like to do eventually, is to do this:

>>> import matplotlib
>>> import random
>>> matplotlib.use('agg')
>>> import matplotlib.pyplot as plt
>>> import random
>>> fig, ax = plt.subplots()
>>> ax.plot([1,2,3], [4,5,6], (random.random(), random.random(), random.random()))

Can someone help me out? Thanks

Upvotes: 1

Views: 24686

Answers (2)

scriptmonster
scriptmonster

Reputation: 2771

To get random color:

import numpy as np
ax.plot([1,2,3], [4,5,6], color=np.random.rand(3,1))

Upvotes: 12

Robᵩ
Robᵩ

Reputation: 168626

How about this:

ax.plot([1,2,3], [4,5,6], color=(.4, .5, .6))

Reading from the documentation,

You do not need to use format strings, which are just abbreviations. All of the line properties can be controlled by keyword arguments. For example, you can set the color, marker, linestyle, and markercolor with:

plot(x, y, color='green', linestyle='dashed', marker='o',
     markerfacecolor='blue', markersize=12).

Upvotes: 2

Related Questions