FaCoffee
FaCoffee

Reputation: 7909

Python: draw scatter with marker size coming from a dictionary?

Say I have a regular grid of nxn points, and a dictionary telling me how many times something happens in each one of the points:

d={
 (0, 0): 1114,
 (0, 1): 270,
 (3, 2): 217,
 (5, 6): 189,
 (10, 10): 164}

I want to plot a scatter of these points, the size of the markers being assigned by the corresponding value of the dict. How can I do this?

I know I can draw a scatter like this, but how to structure s, the list of sizes?

#Import section
#defining d
xticks = [0,1,2,3,4,5,6,7,8,9,10]
yticks = [0,1,2,3,4,5,6,7,8,9,10]
plt.xticks(xticks)
plt.yticks(yticks)
plt.xlabel("x")
plt.ylabel("y",rotation=0)
plt.title('my map')
s=[] #How to structure this?
plt.scatter(x, y,color='yellow',s=s)
plt.show()

Upvotes: 0

Views: 729

Answers (1)

Tadhg McDonald-Jensen
Tadhg McDonald-Jensen

Reputation: 21453

X Y and S are all parallel lists, so for every x[n] will corrospond to y[n] and s[n]. You can just iterate over the dictionary and append to all three lists simultaneously:

x_arr,y_arr,s_arr = [], [], []
for (x,y),s in d.items():
    x_arr.append(x)
    y_arr.append(y)
    s_arr.append(s)
plt.scatter(x_arr, y_arr,color='yellow',s=s_arr)

There are probably more efficient ways of accomplishing this but this demonstrates how the input should be structured.

Upvotes: 2

Related Questions