【问题标题】:3D Scatterplot with strings in PythonPython中带有字符串的3D散点图
【发布时间】:2019-06-04 09:37:30
【问题描述】:

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

以下示例引发错误: 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)

【问题讨论】:

    标签: python-3.x matplotlib scatter3d


    【解决方案1】:

    您正在尝试将分类值(字符串)作为 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 的第一个选项允许您在一行中执行相同的操作。

    【讨论】:

    • 有错字吗? yticks=range(len(xs)), yticklabels=xs,如果 len(xs) ! = len(ys)?
    猜你喜欢
    • 2018-01-13
    • 1970-01-01
    • 2016-12-30
    • 2016-12-22
    • 2023-03-08
    • 2014-11-07
    • 1970-01-01
    • 1970-01-01
    • 2016-11-08
    相关资源
    最近更新 更多