簡體   English   中英

如何使用來自兩個字典的數據創建散點圖 plot?

[英]How do I create a scatter plot using data from two dictionaries?

在我的代碼中,用戶導入了一個包含四列和不斷變化的行數的數據文件。 第一列包含動物的名稱,第二列包含其在字段中的 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 位置值來創建散點圖 plot? 我希望每個鍵(動物)的數據點是不同的顏色。

不確定這是否是您的意思,但這里什么都沒有:

首先我制作了一個文件(animal.txt),我可以將其作為 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

然后我用以下代碼繪制了數據:

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'])

如果您不知道需要多少 colors,您可以從我在頂部導入的名為cnames的列表中動態創建 mpl colors 列表。 然后,您可以根據animals列表的長度縮短該完整列表,如下所示: colors = cnames[:len(animals)]

希望這可以幫助。 不過,您需要弄清楚如何讓您的 plot 實際上看起來不錯:這是3D在 matplotlib 中繪圖的文檔。

編輯:

不記得cnames是一本字典。 對於動態顏色選擇,您需要這樣做:

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.

傳說:Bruh,您需要自己更好地搜索這些東西......長答案: 在 3D 散點圖中添加一個圖例,並在 Matplotlib 中使用 scatter() 簡短的回答,因為我是這樣一個冷酷的家伙:

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.

現在我的贊成票在哪里?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM