在matplotlib中使用for循环时如何自定义颜色图例,分散

在matplotlib中使用for循环时如何自定义颜色图例,分散,matplotlib,categories,legend,colorbar,scatter,Matplotlib,Categories,Legend,Colorbar,Scatter,我想画一个3D散点图,其中数据按组着色。以下是数据示例: aa=pd.DataFrame({'a':[1,2,3,4,5], 'b':[2,3,4,5,6], 'c':[1,3,4,6,9], 'd':[0,0,1,2,3], 'e':['abc','sdf','ert','hgf','nhkm']}) 这里,a,b,c是x,y,z轴。e是散点图中显示的文本。

我想画一个3D散点图,其中数据按组着色。以下是数据示例:

aa=pd.DataFrame({'a':[1,2,3,4,5],
                 'b':[2,3,4,5,6],
                 'c':[1,3,4,6,9],
                 'd':[0,0,1,2,3],
                 'e':['abc','sdf','ert','hgf','nhkm']})
这里,a,b,c是x,y,z轴。e是散点图中显示的文本。我需要将数据分组并显示不同的颜色

这是我的密码:

fig = plt.figure()
ax = fig.gca(projection='3d')
zdirs = aa.loc[:,'e'].__array__()
xs = aa.loc[:,'a'].__array__()
ys = aa.loc[:,'b'].__array__()
zs = aa.loc[:,'c'].__array__()
colors = aa.loc[:,'d'].__array__()
colors1=np.where(colors==0,'grey',
                 np.where(colors==1,'yellow',
                          np.where(colors==2,'green',
                                   np.where(colors==3,'pink','red'))))
for i in range(len(zdirs)): #plot each point + it's index as text above
    ax.scatter(xs[i],ys[i],zs[i],color=colors1[i])
    ax.text(xs[i],ys[i],zs[i],  '%s' % (str(zdirs[i])), size=10, zorder=1, color='k')
ax.set_xlabel('a')
ax.set_ylabel('b')
ax.set_zlabel('c')
plt.show()
但我不知道如何在情节上加上一个传奇。我希望我的传奇是:

颜色和编号应匹配并按顺序排列


有谁能帮我定制颜色栏吗?

首先,我冒昧地减少了您的代码:

  • 我建议创建一个ListedColormap to map integer->color,它允许您通过
    c=aa['d']
    传递颜色列(注意它是
    c=
    ,而不是
    color=
    !)
  • 您不需要在此处使用
    \uuuu数组()
    ,在下面的代码中,您可以直接使用
    aa['a']
  • 最后,您可以为ListedColormap中的每种颜色添加一个空散点图,然后通过
    ax.legend()
将熊猫作为pd导入
将matplotlib.pyplot作为plt导入
从mpl_toolkits.mplot3d导入Axes3D
将numpy作为np导入
从matplotlib.colors导入ListedColormap
将matplotlib.patches作为MPatch导入
aa=pd.DataFrame({'a':[1,2,3,4,5],
‘b’:[2,3,4,5,6],
‘c’:[1,3,4,6,9],
“d”:[0,0,1,2,3],
‘e’:[‘abc’、‘sdf’、‘ert’、‘hgf’、‘nhkm’])
图=plt.图()
ax=图gca(投影=3d')
cmap=ListedColormap([‘灰色’、‘黄色’、‘绿色’、‘粉色’、‘红色’]))
最大散射(aa['a'],aa['b'],aa['c'],c=aa['d'],cmap=cmap)
对于x、y、z,拉链标签(aa['a'],aa['b'],aa['c'],aa['e']):
ax.text(x,y,z,label,size=10,zorder=1)
#通过*空*散点图创建图例
[i在范围(len(aa))内的[ax.散射([],[],c=cmap(i),label=str(i)]]
ax.图例()
ax.set_xlabel('a')
ax.set_ylabel('b'))
ax.set_zlabel('c'))
plt.show()