9

I have a dictionary that looks like this:

test = {1092268: [81, 90], 524292: [80, 80], 892456: [88, 88]}

Now I want to make a simple plot from this dictionary that looks like:

test = {1092268: [x, y], 524292: [x, y], 892456: [x, y]}

So i guess I need to make two lists i.e. x=[] and y=[] and the first value of the list in the dictionary goes to x and the second to y. So I end up with a figure with points (81,90) (80,80 and (88,88). How can I do this?

2
  • No, as long as the x and corresponding y values are together: (81, 90), (80, 80) and (88, 88) Commented May 3, 2015 at 12:22
  • @Joel do you have access to the matplotlib library? Commented May 5, 2015 at 1:59

3 Answers 3

14

Use matplotlib for plotting data

Transform the data into lists of numbers (array-like) and use scatter() + annotate() from matplotlib.pyplot.

%matplotlib inline
import random
import sys
import array
import matplotlib.pyplot as plt

test = {1092268: [81, 90], 524292: [80, 80], 892456: [88, 88]}

# repackage data into array-like for matplotlib 
# (see a preferred pythonic way below)
data = {"x":[], "y":[], "label":[]}
for label, coord in test.items():
    data["x"].append(coord[0])
    data["y"].append(coord[1])
    data["label"].append(label)

# display scatter plot data
plt.figure(figsize=(10,8))
plt.title('Scatter Plot', fontsize=20)
plt.xlabel('x', fontsize=15)
plt.ylabel('y', fontsize=15)
plt.scatter(data["x"], data["y"], marker = 'o')

# add labels
for label, x, y in zip(data["label"], data["x"], data["y"]):
    plt.annotate(label, xy = (x, y))

scatter plot

The plot can be made prettier by reading the docs and adding more configuration.


Update

Incorporate suggestion from @daveydave400's answer.

# repackage data into array-like for matplotlib, pythonically
xs,ys = zip(*test.values())
labels = test.keys()   

# display
plt.figure(figsize=(10,8))
plt.title('Scatter Plot', fontsize=20)
plt.xlabel('x', fontsize=15)
plt.ylabel('y', fontsize=15)
plt.scatter(xs, ys, marker = 'o')
for label, x, y in zip(labels, xs, ys):
    plt.annotate(label, xy = (x, y))
Sign up to request clarification or add additional context in comments.

Comments

5

This works in both python 2 and 3:

x, y = zip(*test.values())

Once you have these you can pass them to a plotting library like matplotlib.

1 Comment

good pythonic suggestion! I updated my answer to show both; I kept the original implementation for those who have not yet learned about all the various iterating shortcuts.
0
def plot(label, x, y):
    ...

for (key, coordinates) in test.items():
    plot(key, coordinates[0], coordinates[1])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.