如何使用两个字典中的数据创建散点图? [英] How do I create a scatter plot using data from two dictionaries?

查看:62
本文介绍了如何使用两个字典中的数据创建散点图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中,用户导入了一个具有四列和不断变化的行数的数据文件.第一列包含动物的名称,第二列包含其在字段中的x位置,第三列包含其y位置,第四列包含其z位置.

In my code, the user imports a data file with four columns and a changing number of rows. The first column contains the name of an animal, the second column contains its x location in a field, the third column contains its y location, and the fourth column contains its z location.

#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位置制作了字典.

I have used dictionaries to create set of keys and values. My keys are the animals and the values are their locations. I have made a dictionary for X,Y, and Z locations.

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位置值来创建散点图?我希望每个键(动物)的数据点都采用不同的颜色.

推荐答案

不确定这是否是您的意思,但是什么也没做:

Not sure if this is what you mean, but here goes nothing:

首先,我制作了一个文件(animal.txt),可以将其导入为数据框:

First I made a file (animal.txt) I can import as a dataframe:

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

然后我用以下代码绘制数据:

Then I plotted the data with the following code:

import matplotlib.pyplot as plt
from matplotlib.colors import cnames
from mpl_toolkits.mplot3d import Axes3D
import pandas as pd

# Create a 3D axes object
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Read in file while naming the columns and specifying the dtype through 'name'
df = pd.read_csv('animals.txt',
                 delim_whitespace=True,
                 names={'animal':str,'x':int,'y':int,'z':int})

# color names for matplotlib
colors = ('r','b','g','y','orange','purple','k')
# Find all animals
animals = df.animal.unique()
# Create a dictionary that correlates animals and colors
cdict = dict(zip(animals, colors))
# Append new column 'colors' to dataframe
df['color'] = [cdict[ani] for ani in df['animal']]
# Plot
ax.scatter(xs=df['x'],
           ys=df['y'],
           zs=df['z'],
           c=df['color'])

如果您不知道需要多少种颜色,则可以从我在顶部导入的名为cnames的列表中动态创建mpl颜色的列表.然后,您可以根据列表animals的长度,用像colors = cnames[:len(animals)]这样的切片来缩短完整列表.

If you don't know how many colors you'll be needing, you can dynamically create a list of mpl colors from the list called cnames which I imported at the top. Then you can just shorten that full list according to the length of the list animals with a slice like: colors = cnames[:len(animals)].

希望这会有所帮助.不过,您需要弄清楚如何使自己的情节看起来像样得体:这是

Hope this helps. You'll need to figure out how to make your plot actually look decent yourself, though: Here's the docs for 3D plotting in matplotlib.

不记得cnames是字典.对于动态颜色选择,您需要执行以下操作:

Didn't remember that cnames was a dictionary. For dynamic color selection you need to do this:

colors = list(cnames.keys())[10:len(animals)+10]
# The 10 is arbitrary. Just don't use number that are too high, because
# you color list might be too short for you number of animals.

传奇人物:布鲁尔,您需要更好地自己搜索这些东西...长答案:

The legend: Bruh you need to google this stuff better yourself... Long answer: Add a legend in a 3D scatterplot with scatter() in Matplotlib. Short answer, cuz I'm a chill dude like that:

from matplotlib.lines import Line2D as custm
# additional import statement so you can make a custom 2DLine object

legend_labels = [custm([0],
                       [0],
                       linestyle="none",
                       c=colors[i],
                       marker='o') 
                       for i in range(len(animals))]

# List comprehension that creates 2D dots for the legend dynamically. 

ax.legend(legend_labels, animals, numpoints = 1)
# attach the legend to your plot.

现在我的投票在哪里?

这篇关于如何使用两个字典中的数据创建散点图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆