根据特定列更改 3D 散点图颜色

Changing 3D scatter plot color based on specific column

我有一些信息示例,如下所示,我想根据 "clusters"(例如 0,1,2)

制作具有不同散点颜色的 3D 散点图
ID    TP    ALB   BUN   clusters
1     153   101  698    1
2     100   90   400    0
3     50    199  500    1
4     113   102  340    2

目前我尝试过:

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure(figsize=(10, 8))
ax1 = fig.add_subplot(111,projection='3d')

for i in range(len(df_tr)):
    x, y, z = df_tr.iloc[i]['BUN'], df_tr.iloc[i]['ALB'], df_tr.iloc[i]['TP']
    ax1.scatter(x, y, z, c=['blue'])
    ax1.text(x, y, z, '{0}'.format(df_tr.iloc[i] 
    ['clusters']), size=12)

ax1.set_xlabel('BUN')
ax1.set_ylabel('ALB')
ax1.set_zlabel('TP')   

ax1.legend('012')
plt.show()

得到散点的结果有聚类信息(0,1,2),但是有没有用Axes3D根据特定列的ifnormation改变散点颜色?

根据你期望的clusters不同的预期数量(只要不是很高)制作一个颜色列表,例如

colors = ['blue', 'green', 'red']

然后只需使用 clusters 值作为列表的索引来获取颜色;

colors = ['blue', 'green', 'red']
for i in range(len(df_tr)):
    x, y, z = df_tr.iloc[i]['BUN'], df_tr.iloc[i]['ALB'], df_tr.iloc[i]['TP']
    ax1.scatter(x, y, z, c=colors[int(df_tr.iloc[i]['clusters'])])