多样本的3D表面绘图

1 投票
1 回答
939 浏览
提问于 2025-04-18 07:16

我有一个CSV文件,里面有很多行和列。比如说,我有一个这样的CSV(用制表符分隔)文件:

    Sample1 Sample2 Sample3 Sample4 Sample5
Log1    2.3 3.3 4.5 5.6 6.7
Log2    3.5 6.7 10.0    22.1    30
Log3    4.2 4.5 6.7 8.9 9.1
Log4    4.5 8.9 10.2    11.8    14.7

我查看了pylab库中的表面图方法,链接在这里,但我觉得我想做的和他们给出的例子不太一样。因为我想让X轴显示CSV文件第一列的名字(Log1, Log2...Log4),而Y轴显示列名(例如Sample1, Sample2, ... Sample5)。值将决定3D图的表面样子。

所以我想知道如何在Python或其他工具中制作3D表面图?任何回复都会很感激。

编辑:

感谢@anon的回答,我写了以下Python代码,但我不太清楚如何将CSV文件中的值分配给(X, Y, Z)坐标。我现在的做法是通过x_axis的大小(X标签的列表)和y_axis的大小(Y标签的列表)来分配X和Y值,Z值则是来自CSV文件的实际数字。但我下面的代码不工作——需要一些额外的帮助。

csv_file_path='/path/to/my/CSV/my_file.csv'    
mFile = open(csv_file_path, 'rb')
datafile = list(csv.reader(mFile, delimiter='\t'))

x_ax = []  # a list of X labels
y_ax = []  # a list of Y labels
row_data = []  # a list of row values 
Z = []     # a list of row_data


first_line = True  # skip the first line which is the header

for row in datafile:
    print row[0]
    summ = 0

    if first_line:
        y_ax = row[1:]
        print y_ax
        first_line = False
        continue

    x_ax.append(row[0])
    row_data = row[1:]
    data.append(row_data)

X = range(len(x_ax))   # use the length of x_ax as the X coordinate
Y = range(len(y_ax))   # use the length of y_ax as the Y coordinate


fig = plt.figure(figsize=(200, 6))
ax = fig.add_subplot(1, 2, 1, projection='3d')
ax.set_xticklabels(x_ax)
ax.set_yticklabels(y_ax)
ax.set_title("Frequencies Surface Plotting")

surf = ax.plot_surface(X, Y, data, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)
ax.set_zlim(0, 100)
fig.colorbar(surf, shrink = 0.5, aspect = 5)

plt.show()

Pylab的例子:

在这里输入图片描述

1 个回答

2

你可以把 xy 轴的标签改成你想要的内容。例如:

fig = plt.figure(figsize=(14,6))
ax = fig.add_subplot(1, 2, 1, projection='3d')
x_ax = ["Log1", "Log2"] # etc ... just parse what you need from the CSV file
ax.set_xticklabels(x_ax)
y_ax = ["Sample1","Sample2"] # etc... just parse what you need from the CSV file
ax.set_yticklabels(y_ax)
plt.show()

这样做会产生:

改变后的轴

这就是你想要的吗?

撰写回答