tubadc
tubadc

Reputation: 772

How to add lines from 0,0 to each scatter plot point using matplotlib?

I'm trying to recreate the following chart with matplotlib, but I can't figure it out how to create the lines from the 0,0(origin) to each point

enter image description here

my current code is:

plt.figure(figsize=(10,7))
plt.grid()
plt.xlabel('Movie 1')
plt.ylabel('Movie 2')
A = [1.0, 2.0]
B = [2.0, 4.0]
C = [2.5, 4.0]
D = [4.5, 5.0]
xs = [A[0], B[0], C[0], D[0]]
ys = [A[1], B[1], C[1], D[1]]

users = ['A', 'B', 'C', 'D']

for i, user in enumerate(users):
    x = xs[i]
    y = ys[i]
    plt.scatter(x, y, marker = 'o')
    plt.plot(x,y,0,0, linestyle = '--' )
    plt.text(x+0.01, y+0.01, user, fontsize=19)
    
plt.xlim(0,7)
plt.ylim(0,7)


plt.show()

The code only returns the points, but with no lines... how do I create the lines?

Thanks!

Upvotes: 0

Views: 1872

Answers (1)

Lucas Roy
Lucas Roy

Reputation: 133

you can do this by plotting the lines manually in your for loop:

for i, user in enumerate(users):
    x = xs[i]
    y = ys[i]
    plt.scatter(x, y, marker = 'o')

    # V this adds the lines V
    plt.plot([0,xs[i]], [0, ys[i]], color="black")
    # ^ this adds the lines ^

    plt.plot(x,y,0,0, linestyle = '--' )
    plt.text(x+0.01, y+0.01, user, fontsize=19)

which results in this graph

Upvotes: 1

Related Questions