【问题标题】:How do I create a scatter plot using data from two dictionaries?如何使用来自两个字典的数据创建散点图?
【发布时间】: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


    【解决方案1】:

    不确定这是不是你的意思,但这里什么都没有:

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

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

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

    希望这会有所帮助。不过,您需要弄清楚如何让您的绘图看起来确实不错:这是 docs 用于 matplotlib 中的 3D 绘图。

    编辑:

    不记得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,你需要自己更好地用谷歌搜索这些东西......长答案:Add a legend in a 3D scatterplot with scatter() in Matplotlib。 简短的回答,因为我是这样一个冷酷的家伙:

    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.
    

    现在我的赞成票在哪里?

    【讨论】:

    • 这不是我要问的,但它工作得很好,只需一点点操作,我想我可以把它准确地送到我需要它去的地方。谢谢!我正在努力让“colors = cnames[:len(animals)]”工作,我将如何在这个情节中添加一个图例来告诉我哪种动物是哪种颜色? @J.Doe
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-07
    • 2015-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多