使用matplotlib和Axes3D标记打印日期

时间:2019-04-19 22:15:40

标签: python matplotlib

如何像上面的图片一样为我的Axes3D图添加命名?我的图片如下:

Axes3D

这是我的代码:

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X_train['width'], X_train['height'], X_train['color_score'], c=y_train, marker='o', s=100)
ax.set_xlabel('width')
ax.set_ylabel('height')
ax.set_zlabel('color_score')
plt.show()

我必须添加什么才能使底部图形的名称排在顶部图形的顶部? Matplotlib对于新手来说有点令人困惑,因此显示具有哪种格式的代码行将超级有帮助。

1 个答案:

答案 0 :(得分:1)

我认为ax.text()在做什么。参见here的几个示例。

在给定数据的情况下,要想可靠地推断出文本的良好(易于阅读)放置可能是一项挑战。一个幼稚的方法如下所示(未测试代码):

offset = [0, 0, 0.05]
for label in y_train.unique():          
    idx = (y_train==label)
    posX = X['width'][idx].mean() + offset[0]
    posY = X['height'][idx].mean() + offset[1]
    posZ = X['color_score'][idx].mean() + offset[2]
    ax.text(x=posX, y=posY, z=posZ, s=label, zdir=None)

如果您使用的是熊猫,代码可能类似于以下内容:

X['labels'] = y_train
grouping = X.groupby('labels')
for label, group in grouping:
    center = group[['width', 'height', 'color_score']].mean(axis=0).values
    center += np.asarray(offset)
    ax.text(x=center[0], y=center[1], z=center[2], s=label, zdir=None)