如何根据从 CSV 文件中获取的文本而不是数字在 MatPlotLib 上绘制轴?

How can I plot an axis on MatPlotLib in terms of text, not numbers, taken from a CSV file?

我有一个 .csv 文件,看起来像这样(小样本,忽略句点):

Year | Month | Carrier | Elapsed Time

1987 | 10.......|UN.......|15

1987 | 11.......|AM.......|17

1987 | 12.......|HK.......|20

我正在 MatPlotLib (Python) 中绘制 3D 图形,其中 z 轴(垂直轴)是运行时间,x 轴是月份,y 轴是载体。如果我没记错的话,MatPlotLib 只允许每个轴的值是整数而不是字符串。这就是问题所在:载体值是字符串或字母,例如 UN、AM 和 HK。到目前为止我的代码是:

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

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

readFile = open('/home/andrew/Downloads/1987.txt', 'r')
sepFile = readFile.readlines()[1:50000]
readFile.close()

rect = fig.patch
rect.set_facecolor('white')

X = []
Y = []
Z = []

for plotPair in sepFile:
    xAndY = plotPair.split(',')
    X.append(int(xAndY[1]))
    Y.append(str(xAndY[2])) #Putting str() instead of int() didn't solve the problem
    Z.append(int(xAndY[3]))

ax.scatter(X,Y,Z, c ='r', marker='o')

ax.set_xlabel('x axis')
ax.set_ylabel('y axis')
ax.set_zlabel('z axis')

plt.show()

我知道我可以说 x = [UN, AM, HK] 但问题是 x 列表不会从 .csv 文件中获取。 Python 程序不知道哪个点属于哪个运营商名称。我希望能够告诉 Python 为每个点搜索带有运营商名称的列,然后能够提取该信息,以便它可以从 csv 文件中成功绘制,如图所示:

3D Graph Skeleton

我还是个新手,还没有掌握 Python 的窍门,所以非常感谢您抽出时间来回答。非常感谢您的帮助。

我会让 Y 轴成为一个整数范围,然后使用您的字符串列表设置 yticklabels。类似于:

X = []
Y = []
Z = []
Ylabels = []

for plotPair in sepFile:
    xAndY = plotPair.split(',')
    X.append(int(xAndY[1]))
    Y.append(range(len(xAndY[2]))
    Ylabels.append(str(xAndY[2]))
    Z.append(int(xAndY[3]))

ax.scatter(X,Y,Z, c ='r', marker='o')

ax.set_xlabel('x axis')
ax.set_ylabel('y axis')
ax.set_zlabel('z axis')

ax.set_yticks(Y)
ax.set_yticklabels(Ylabels)

感谢 Tom 的回答,这只是一个改编。

此外,我很确定那里有更好的答案,但这应该适用于您正在做的事情。

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

X = {}
Z = {}

for plotPair in sepFile:
    xAndY = plotPair.split(',')
    label = str(xAndY[2])

    if label in x.keys():
        X[label].append(int(xAndY[1]))
        Z[label].append(int(xAndY[3]))
    else:
        X[label] = [int(xAndY[1])]
        Z[label] = [int(xAndY[3])] 

Y=0
for label in X.keys():
    ax.scatter(X[label],Y[-1]*np.ones_like(X[label]),Z[label], c ='r', marker='o')
    Y.append(Y[-1]+1)

ax.set_xlabel('x axis')
ax.set_ylabel('y axis')
ax.set_zlabel('z axis')

ax.set_yticks(Y)
ax.set_yticklabels(X.keys())

一个好处是每个载体可以有不同的颜色。