python-如何仅给n(例如3)种颜色随机分配给python中的散点图?

时间:2019-05-29 12:16:32

标签: python matplotlib colors scatter-plot scatter3d

生成的随机数x,y,z,然后将它们放入散点图3d图中,但无法绘制点,并随机使用3种特定颜色(例如红色,黑色,黄色)。

matplotlib.pyplot.scatter的文档中,除了第一种颜色之外,我无法理解其他三种指定颜色的方法。

代码:

import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D

x, y, z = np.random.rand(3,50)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x,y,z,marker='.',color='b')

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()

1 个答案:

答案 0 :(得分:1)

如果您只想随机分配n种颜色中每个点的颜色,则可以这样做:

import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D

x, y, z = np.random.rand(3,50)
n=3
colors = np.random.randint(n, size=x.shape[0])

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x,y,z,marker='.',c=colors)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()