【发布时间】:2019-11-15 01:20:48
【问题描述】:
在我的代码中,用户导入了一个包含四列和不断变化的行数的数据文件。第一列包含动物的名称,第二列包含其在字段中的 x 位置,第三列包含其 y 位置,第四列包含其 z 位置。
#load the data
emplaced_animals_data = np.genfromtxt('animal_data.txt', skip_header = 1, dtype = str)
print(type(emplaced_animals_data))
print(emplaced_animals_data)
<class 'numpy.ndarray'>
[['butterfly' '1' '1' '3']
['butterfly' '2' '2' '3']
['butterfly' '3' '3' '3']
['dragonfly' '4' '1' '1']
['dragonfly' '5' '2' '1']
['dragonfly' '6' '3' '1']
['cat' '4' '4' '2']
['cat' '5' '5' '2']
['cat' '6' '6' '2']
['cat' '7' '8' '3']
['elephant' '8' '9' '3']
['elephant' '9' '10' '4']
['elephant' '10' '10' '4']
['camel' '10' '11' '5']
['camel' '11' '6' '5']
['camel' '12' '5' '6']
['camel' '12' '3' '6']
['bear' '13' '13' '7']
['bear' '5' '15' '7']
['bear' '4' '10' '5']
['bear' '6' '9' '2']
['bear' '15' '13' '1']
['dog' '1' '3' '9']
['dog' '2' '12' '8']
['dog' '3' '10' '1']
['dog' '4' '8' '1']]
我使用字典来创建一组键和值。我的键是动物,值是它们的位置。我已经为 X、Y 和 Z 位置制作了字典。
animal_list = ['cat', 'elephant', 'camel', 'bear', 'dog']
locsX = []
locsY = []
locsZ = []
animalsX = {}
animalsY = {}
animalsZ = {}
for i in range(0, len(animal_list)):
for j in range(0, len(emplaced_animals_data)):
for k in range(0, len(animal_list)):
if animal_list[i] == animal_list[k] and animal_list[i] == emplaced_animals_data[j,0]:
locsX = np.append(locsX, emplaced_animals_data[j,1])
locsY = np.append(locsY, emplaced_animals_data[j,2])
locsZ = np.append(locsZ, emplaced_animals_data[j,3])
animalsX.update({animal_list[k]:locsX})
animalsY.update({animal_list[k]:locsY})
animalsZ.update({animal_list[k]:locsZ})
print(animalsX)
print(animalsY)
{'cat': array(['4', '5', '6', '7'], dtype='<U32'), 'elephant': array(['4', '5', '6', '7', '8', '9', '10'], dtype='<U32'), 'camel': array(['4', '5', '6', '7', '8', '9', '10', '10', '11', '12', '12'],
dtype='<U32'), 'bear': array(['4', '5', '6', '7', '8', '9', '10', '10', '11', '12', '12', '13',
'5', '4', '6', '15'], dtype='<U32'), 'dog': array(['4', '5', '6', '7', '8', '9', '10', '10', '11', '12', '12', '13',
'5', '4', '6', '15', '1', '2', '3', '4'], dtype='<U32')}
{'cat': array(['4', '5', '6', '8'], dtype='<U32'), 'elephant': array(['4', '5', '6', '8', '9', '10', '10'], dtype='<U32'), 'camel': array(['4', '5', '6', '8', '9', '10', '10', '11', '6', '5', '3'],
dtype='<U32'), 'bear': array(['4', '5', '6', '8', '9', '10', '10', '11', '6', '5', '3', '13',
'15', '10', '9', '13'], dtype='<U32'), 'dog': array(['4', '5', '6', '8', '9', '10', '10', '11', '6', '5', '3', '13',
'15', '10', '9', '13', '3', '12', '10', '8'], dtype='<U32')}
如何使用字典中每个键(动物)的 X 和 Y 位置值来创建散点图?我希望每个键(动物)的数据点是不同的颜色。
【问题讨论】:
标签: python dictionary plot