问题
I can't figure out how to use colours while trying to create a scatter plot in matplotlib.
I'm trying to plot multiple scatter plots with different colour points to show the clusters.
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()
The error I'm getting is as follows:
ValueError: to_rgba: Invalid rgba arg "#" to_rgb: Invalid rgb arg "#" could not convert string to float: #
It seems like its treating these rgb arguments as floats.
However in the matplotlib docs colors are written in this style http://matplotlib.org/api/colors_api.html
What am I missing?
回答1:
Its just a simple typo: You are missing a comma at the end of the first line of colors
(between '#22222f'
and '#eeeff1'
), which means two entries get concatenated into a string that matplotlib
can't interpret as a color.
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
If you add the comma in there, all seems fine.
To get your "MCVE" to work, I had to add the module imports, and assume that groups
has a length the same as 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()
来源:https://stackoverflow.com/questions/33557609/invalid-rgba-arg-in-matplotlib