Skip to content Skip to sidebar Skip to footer

How Do I Create A Scatter Plot Using Data From Two Dictionaries?

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

Solution 1:

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

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

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.

Edit:

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 inrange(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.

Now where's my upvote?

Post a Comment for "How Do I Create A Scatter Plot Using Data From Two Dictionaries?"