在2D图上绘制3D点,从文件中读取值

时间:2015-03-26 18:44:56

标签: python numpy matplotlib

我有一个包含3个坐标的点集的文件,由制表符分隔。像这样(为了可读性添加了空格,原始文件中没有):

x0 \t y0 \t z0
x0 \t y1 \t z1
x1 \t y0 \t z0
x1 \t y1 \t z1
x1 \t y2 \t z2
x2 \t y0 \t z0
...

我想在单个2D图上将它们绘制为单独的线,例如:

line for all points with x=x0, label=x0
line for all points with x=x1, label=x1
line for all points with x=x2, label=x2

绘制具有不同颜色的线条。

我知道numpy有一个很酷的阅读专栏功能,如:

my_data = np.genfromtxt(input_file, delimiter='\t', skiprows=0)
Y = my_data[:, 1]
Z = my_data[:, 2]

是否有基于另一列的值的类似快速和干净的方法来选择列值?

如果没有快速的功能(根据它旁边的x值组成一列),我可以解析文件并逐步构建数据结构。

然后我会做这样的事情,使用Matplotlib:

ax = plt.axes()
ax.set_xlabel('Y')
ax.set_ylabel('Z')

# for each value of X
    # pick Y and Z values
    plt.plot(Y, Z, linestyle='--', marker='o', color='b', label='x_val')

但我确信有更多的Pythonic方式。也许是列表理解的一些技巧?

编辑:这是完整的工作代码(感谢回答的人)。我只需要一种方法让它在不削减传奇的情况下显示

import os
import numpy as np
import matplotlib.pyplot as plt

input_file = os.path.normpath('C:/Users/sturaroa/Documents/my_file.tsv')

# read values from file, by column
my_data = np.genfromtxt(input_file, delimiter='\t', skiprows=0)
X = my_data[:, 0]  # 1st column
Y = my_data[:, 1]  # 2nd column
Z = my_data[:, 2]  # 3rd column

# read the unique values in X and use them as keys in a dictionary of line properties
d = {val: {'label': 'x {}'.format(val), 'linestyle': '--', 'marker': 'o'} for val in set(X)}

# draw a different line for each of the unique values in X
for val, kwargs in d.items():
    mask = X == val
    y, z = Y[mask], Z[mask]
    plt.plot(y, z, **kwargs)

# label the axes of the plot
ax = plt.axes()
ax.set_xlabel('Y')
ax.set_ylabel('Z')

# get the labels of all the lines in the graph
handles, labels = ax.get_legend_handles_labels()

# create a legend growing it from the middle and put it on the right side of the graph
lgd = ax.legend(handles, labels, loc='center left', bbox_to_anchor=(1.0, 0.5))

# save the figure so that the legend fits inside it
plt.savefig('my_file.pdf', bbox_extra_artists=(lgd,), bbox_inches='tight')

plt.show()

2 个答案:

答案 0 :(得分:2)

假设您有value:kwargs对字典,其中valueX必须在该曲线中的值,而kwargs是一个包含参数的字典传递给绘图功能。

下面的代码将使用value构建一个可用于索引和选择适当点的掩码。

import numpy as np
import matplotlib.pyplot as plt


my_data = np.genfromtxt('data.txt', delimiter=' ', skiprows=0)
X = my_data[:, 0]
Y = my_data[:, 1]
Z = my_data[:, 2]

d = {
    0: {'label': 'x0'},
    1: {'label': 'x1'}
}

for val, kwargs in d.items():
    mask = X == val
    y, z = Y[mask], Z[mask]

    plt.plot(y, z, **kwargs)

plt.legend()

plt.show()

enter image description here

答案 1 :(得分:1)

我建议使用词典。首先加载您的数据,

my_data = np.genfromtxt(input_file, delimiter='\t', skiprows=0)
X = my_data[:, 0]
Y = my_data[:, 1]
Z = my_data[:, 2]

然后为每个x:

值创建一个包含数组的字典
Ydict = {}
Zdict = {}
for x in np.unique(X):
    inds = X == x
    Ydict[x] = Y[inds]
    Zdict[x] = Z[inds]

现在你有两个字典,其中的键是X的唯一值(注意使用np.unique),字典的值是X匹配的数组键。

你的情节调用看起来像是,

for x in Ydict:
    plt.plot(Ydict[x], Zdict[x], label=str(x), ...)

您希望将...替换为您想要设置的其他任何线路属性,但如果您希望每条线路都是不同的颜色,请不要使用color='b'

这有帮助吗?