首页 > 解决方案 > Python中带有字符串的3D散点图

问题描述

我尝试在 Python 中使用 x 和 y 上的字符串类别(即神经网络的激活函数和求解器)以及 z 轴上的浮点数(即 NN 的准确度得分)来绘制 3D 散点图。

以下示例引发错误: ValueError: could not convert string to float: 'str1'

我按照此文档进行 3D 绘图: https ://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html

任何想法,可能是什么问题?提前谢谢了!

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
xs=['str1', 'str2']
print(type(xs))
ys=['str3', 'str4']
print(type(ys))
zs=[1,2]
ax.scatter(xs, ys, zs)

标签: python-3.xmatplotlibscatter3d

解决方案


您正在尝试将分类值(字符串)作为 x 和 y 参数传递。这适用于 1d 散点图,但在 3d 中,您需要定义跨度/笛卡尔坐标。您主要想要的是作为 x 和 y 轴刻度标签的字符串。要获得所需的绘图,您可以做的是首先绘制数值,然后根据您的字符串值重新分配刻度标签。

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

xs=['str1', 'str2']
ys=['str3', 'str4']
zs=[1,2]

ax.scatter(range(len(xs)), range(len(xs)), zs)
ax.set(xticks=range(len(xs)), xticklabels=xs,
       yticks=range(len(xs)), yticklabels=xs) 

您还可以使用设置刻度标签

plt.xticks(range(len(xs)), xs)
plt.yticks(range(len(ys)), ys)

然而,使用的第一个选项ax允许您在一行中执行相同的操作。

在此处输入图像描述


推荐阅读