chikitin
chikitin

Reputation: 781

Matplotlib Python 3 is not drawing arrows starting at non-origin

I have the following code that plots the word vectors:

import numpy as np
import matplotlib.pyplot as plt
la = np.linalg

words = ['I', 'like', 'enjoy', 'deep', 'learning', 'NLP', 'flying', '.']
X = np.array([ [0,2,1,0,0,0,0,0],
               [2,0,0,1,0,1,0,0],
               [1,0,0,0,0,0,1,0],
               [0,1,0,0,1,0,0,0],
               [0,0,0,1,0,0,0,1],
               [0,1,0,0,0,0,0,1],
               [0,0,1,0,0,0,0,1],
               [0,0,0,0,1,1,1,0]])
U, s, Vh = la.svd(X, full_matrices = False)
ax = plt.axes()
for i in range(len(words)): 
    plt.text(U[i,0],U[i,1],words[i])
    ax.arrow(0,0,U[i,0],U[i,1],head_width=0.1, head_length=0.1, fc='lightblue', ec='black')
plt.xlim(-.8,.2)
plt.ylim(-.8,.8)
plt.grid()

plt.title(' Simple SVD word vectors in Python',fontsize=10)
plt.show()
plt.close()

enter image description here

This draws the arrows starting from the origin. However, when I try to plot if from other points.

ax.arrow(-0.8,-0.8,U[i,0],U[i,1],head_width=0.1, head_length=0.1, fc='lightblue', ec='black')

enter image description here

It does not draw the arrows! What is the issue please?

Thank you.

Upvotes: 0

Views: 671

Answers (1)

Trenton McKinney
Trenton McKinney

Reputation: 62533

Using matplotlib.axes.Axes.arrow:

  • This draws an arrow from (x, y) to (x+dx, y+dy)
  • Setting (-0.8, -0.8), gets the following

enter image description here

  • In order to change the direction of the arrow, you have to compensate for a non-zero origin
  • With the following line:
ax.arrow(-0.8, -0.8, (U[i,0] + 0.8), (U[i,1] + 0.8),head_width=0.1, head_length=0.1, fc='lightblue', ec='black')
  • Will get you this:

enter image description here

Upvotes: 2

Related Questions