Python 中带有字符串的 3D 散点图 [英] 3D Scatterplot with strings in Python

查看:43
本文介绍了Python 中带有字符串的 3D 散点图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

以下示例引发错误:ValueError: 无法将字符串转换为浮点数:'str1'

我遵循了 3D 绘图的这个文档:

I tried to do a 3D scatter plot in Python with string categories (i.e. activation functions and solvers for a neural network) on x and y and floating numbers (i.e. accuracy score of NN) on the z axis.

The following example raises the error: ValueError: could not convert string to float: 'str1'

I followed this documentation for 3D plots: https://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html

Any ideas, what might be the problem ? Many thanks in advance!

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)

解决方案

You are trying to pass categorical values (strings) as the x and y arguments. This would work for 1d scatter plot but in 3d, you need to define the span/cartesian coordinates. What you mainly want to have is the strings as the x and y-axis ticklabels. To get the desired plot, what you can do is to first plot the numeric values and then re-assign the ticklabels as per your string values.

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) 

You can also set the tick labels using

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

The first option using ax however allows you to do the same in one line.

这篇关于Python 中带有字符串的 3D 散点图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆