Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot a scatter plot in python with matplotlib with dictionary

I need help plotting a dictionary, below is the data sample data set. I want to create a scatter graph where x:y are (x,y) coordinates and title'x' would be the legend of the graph.. I want to create graphs of below data set so combine all the below data in one graph.

for example: plot title1':{x:y, x:y} in red( or any other color) make a legend(key) saying red(or whatever color) is for title1,

do same for title2:{x:y, x:y} (in a different color)....and so on.

Any help would be greatly appreciated. Thank you.

data = {'title1':{x:y, x:y},title2:{x:y,x:y,x:y},'title3':{x:y,x:y}....}

I also followed this advise, but it was for individual graph. Plotting dictionaries within a dictionary in Myplotlib python

This is what I have tried, i don't have much experience in matplotlib and couldn't find anything useful onlline. Any help would be greatly appreciated.

import matplotlib.pyplot as plt
import numpy as np
d ={'5000cca234c1c445': {382877: 7, 382919: 3},
'5000cca234c94a2e': {382873: 1, 382886: 1},
'5000cca234c89421': {383173: 1, 383183: 2, 382917: 1, 382911: 1},
'5000cca234c5d43a': {382889: 1, 382915: 1, 382917: 8},
'5000cca234c56488': {382909: 2, 382911: 5}}

xval = []
yval= []
ttle = []
print d
for title, data_dict in d.iteritems():
   x = data_dict.keys()
   #print 'title is', title
   #print 'printing x values',x   
   xval = xval + x
   print xval
   y = data_dict.values()
   yval = yval+y
   ttle.append(title)
   print  yval
#print 'printing y values', y         
#plt.figure()
print xval
print yval
print ttle
plt.scatter(xval,yval)
plt.show()
like image 754
user3262210 Avatar asked Feb 17 '14 06:02

user3262210


People also ask

What is the difference between plot () and scatter ()? Python?

The difference between the two functions is: with pyplot. plot() any property you apply (color, shape, size of points) will be applied across all points whereas in pyplot. scatter() you have more control in each point's appearance.


2 Answers

You can try to plot on the loop, and after that show the legend, something like this:

import matplotlib.pyplot as plt

d ={'5000cca234c1c445': {382877: 7, 382919: 3},
'5000cca234c94a2e': {382873: 1, 382886: 1},
'5000cca234c89421': {383173: 1, 383183: 2, 382917: 1, 382911: 1},
'5000cca234c5d43a': {382889: 1, 382915: 1, 382917: 8},
'5000cca234c56488': {382909: 2, 382911: 5}}

colors = list("rgbcmyk")

for data_dict in d.values():
   x = data_dict.keys()
   y = data_dict.values()
   plt.scatter(x,y,color=colors.pop())

plt.legend(d.keys())
plt.show()
like image 191
Alvaro Fuentes Avatar answered Oct 16 '22 12:10

Alvaro Fuentes


Try this:

data = {'title1':{x:y, x:y},title2:{x:y,x:y,x:y},'title3':{x:y,x:y}....}

plt.scatter(*zip(*data.items()))
plt.show()
like image 33
chanda singh Avatar answered Oct 16 '22 11:10

chanda singh