Python 中字符串的 3D 散点图
3D Scatterplot with strings in Python
我尝试在 Python 中绘制 3D 散点图,在 x 和 y 上使用字符串类别(即神经网络的激活函数和求解器),在 z 上使用浮点数(即 NN 的准确度分数)轴.
以下示例引发错误:
ValueError:无法将字符串转换为浮点数:'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)
您正在尝试将分类值(字符串)作为 x 和 y 参数传递。这适用于 1d 散点图,但在 3d 中,您需要定义 span/cartesian 坐标。您主要想要的是作为 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
的第一个选项允许您在一行中执行相同的操作。
我尝试在 Python 中绘制 3D 散点图,在 x 和 y 上使用字符串类别(即神经网络的激活函数和求解器),在 z 上使用浮点数(即 NN 的准确度分数)轴.
以下示例引发错误: ValueError:无法将字符串转换为浮点数:'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)
您正在尝试将分类值(字符串)作为 x 和 y 参数传递。这适用于 1d 散点图,但在 3d 中,您需要定义 span/cartesian 坐标。您主要想要的是作为 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
的第一个选项允许您在一行中执行相同的操作。