从tex将数据打印为3d函数

2024-04-18 20:35:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个以下格式的文本文件。你知道吗

1 10 3
1  9 2
1  4 5
2 10 2  
2  6 5
3  4 3  
3  5 4
3  8 1

第一列代表玩家。有3个教练。第二列代表玩家。总共有10名选手。第三栏代表不同教练给每位球员的分数(最低可以是1分,最高可以是5分)。注意,并不是所有的玩家都被评分,只有一些玩家被评分。我基本上想在python中为我拥有的数据绘制一个3d函数。你知道吗

我想知道做这件事最好的方法是什么?你知道吗

我的方法

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

with open("test.txt") as f:
    data = f.read()

data = data.split('\n')

x = [row.split(' ')[0] for row in data]
y = [row.split(' ')[1] for row in data]
z = [row.split(' ')[2] for row in data]

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')


ax.scatter(x, y, z, c='r', marker='o')

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()

我的错误

  File "solution.py", line 10, in <module>
    y = [row.split(' ')[1] for row in data]
IndexError: list index out of range

Tags: 方法inimportfordataas玩家plt
1条回答
网友
1楼 · 发布于 2024-04-18 20:35:51

默认情况下,Split在whitespace上工作。当一次拆分产生所有3个值时,对每个变量再次执行拆分也是一种浪费,而且会给你一个低分。当然,如果某个玩家没有被评分,你需要在提取评分之前检查一下:

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

with open("test.txt") as f:
    for row in f:
        coordinate = row.split()
        if len(coordinate) < 3: # an empty line or don't have a grade
            continue

        ax.scatter(*coordinate, c='r', marker='o')

plt.show()

您还可以在3个列表中累积x、y和z,并通过一个调用绘制散点图,但我认为为每行绘制一个点的代码更少=更优雅。你知道吗

相关问题 更多 >