Python 在二维打印上绘制三维点从文件读取值
我有一个包含3个坐标的点集的文件,由制表符分隔。如下所示(为可读性而添加的空格,原始文件中不存在): 我想在单个2D绘图上将它们绘制为单独的线,如:Python 在二维打印上绘制三维点从文件读取值,python,numpy,matplotlib,Python,Numpy,Matplotlib,我有一个包含3个坐标的点集的文件,由制表符分隔。如下所示(为可读性而添加的空格,原始文件中不存在): 我想在单个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.genf
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')
但我相信有一种更像蟒蛇的方式。也许有一些关于列表理解的技巧
编辑:这是完整的工作代码(感谢回答的人)。我只需要一种不破坏传奇的方式来展示它
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()
假设您有一个包含
value:kwargs
对的字典,其中value
是X
必须在该曲线中使用的值,kwargs
是保存要传递给绘图函数的参数的dict
下面的代码将使用值
构建一个掩码,该掩码可用于索引和选择适当的点
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()
我建议使用字典。从加载数据开始
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'
这有帮助吗?更好的是,用dict理解初始化
d
:d={val:{'label':'x'+str(val),'linestyle':'-'}在np.unique(x)}
中为val初始化d
,然后您可以更改后续行中每行的其他属性,例如d[0]['color']='b'
,和d[1][/color']='r'
。您可能会喜欢熊猫图书馆;它非常擅长对表格数据进行排序和分组,并绘制结果。下面是一个相关的例子:
for x in Ydict:
plt.plot(Ydict[x], Zdict[x], label=str(x), ...)