将随机颜色分配给matplotlib图

问题描述 投票:1回答:2

我正在尝试在matplotlib中绘制一些多边形,并且已经能够使用预定义的HTML颜色,但是我想使用随机的RGB元组。但是,我无法弄清楚。

这是我一直在尝试的代码:

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

我收到此错误:raise ValueError('third arg must be a format string')

我最终想做的就是做到这一点:

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

有人可以帮我吗?谢谢

python python-2.7 matplotlib rgb
2个回答
2
投票

怎么样:

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

the documentation中读取,

您不需要使用格式字符串,这只是缩写。所有的行属性都可以由关键字参数控制。例如,您可以使用以下方法设置颜色,标记,线型和标记颜色:

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

7
投票

获得随机颜色:

import numpy as np
ax.plot([1,2,3], [4,5,6], color=np.random.rand(3,1))
© www.soinside.com 2019 - 2024. All rights reserved.