在尝试在matplotlib中创建散点图时,我无法弄清楚如何使用颜色。
我试图绘制具有不同色点的多个散点图以显示群集。
colors=['#12efff','#eee111','#eee00f','#e00fff','#123456','#abc222','#000000','#123fff','#1eff1f','#2edf4f','#2eaf9f','#22222f'
'#eeeff1','#eee112','#00ef00','#aa0000','#0000aa','#000999','#32efff','#23ef68','#2e3f56','#7eef1f','#eeef11']
C=1
fig = plt.figure()
ax = fig.gca(projection='3d')
for fgroups in groups:
X=[np.random.rand(50),np.random.rand(50),np.random.rand(50)]
y=[np.random.rand(50),np.random.rand(50),np.random.rand(50)]
Z=[np.random.rand(50),np.random.rand(50),np.random.rand(50)]
C=(C+1) % len(colors)
ax.scatter(X,Y,Z, s=20, c=colors[C], depthshade=True)
plt.show()
我得到的错误如下:
ValueError:to_rgba:无效的rgba arg"#" to_rgb:无效的rgb arg"#" 无法将字符串转换为float:#
似乎它将这些rgb参数视为浮点数。
然而,在matplotlib docs中,颜色是用这种风格http://matplotlib.org/api/colors_api.html
编写的我错过了什么?
答案 0 :(得分:2)
它只是一个简单的错字:你在colors
的第一行末尾('#22222f'
和'#eeeff1'
之间)缺少一个逗号,这意味着两个条目会连接成一个逗号matplotlib
无法解释为颜色的字符串。
for i in colors:
print i
#12efff
#eee111
#eee00f
#e00fff
#123456
#abc222
#000000
#123fff
#1eff1f
#2edf4f
#2eaf9f
#22222f#eeeff1
#eee112
#00ef00
#aa0000
#0000aa
#000999
#32efff
#23ef68
#2e3f56
#7eef1f
#eeef11
如果你在那里添加逗号,一切似乎都很好。
让你的" MCVE"为了工作,我不得不添加模块导入,并假设groups
的长度与colors
相同:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
colors=['#12efff','#eee111','#eee00f','#e00fff','#123456','#abc222','#000000','#123fff','#1eff1f','#2edf4f','#2eaf9f','#22222f',
'#eeeff1','#eee112','#00ef00','#aa0000','#0000aa','#000999','#32efff','#23ef68','#2e3f56','#7eef1f','#eeef11']
C=1
fig = plt.figure()
ax = fig.gca(projection='3d')
groups = range(len(colors))
for fgroups in groups:
X=[np.random.rand(50),np.random.rand(50),np.random.rand(50)]
Y=[np.random.rand(50),np.random.rand(50),np.random.rand(50)]
Z=[np.random.rand(50),np.random.rand(50),np.random.rand(50)]
C=(C+1) % len(colors)
ax.scatter(X,Y,Z, s=20, c=colors[C], depthshade=True)
plt.show()