No Result
View All Result
DevRescue
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
DevRescue
Home Blog Python

Python Plot Vector with matplotlib

by Khaleel O.
August 23, 2021
in Python
Reading Time: 4 mins read
A A
python plot vector matplotlib
python plot vector matplotlib

We will use python to plot vector graphs with matplotlib. Let’s go! ✨✨

A vector in math is a quantity that describes movement from one point to another. A vector quantity has both magnitude and direction. Graphically, a vector may be drawn as an arrow on a cartesian plane/2-dimensional plane. The magnitude will be the length of the arrow and the direction will be the direction to which the arrow head is pointed.

A Vector

u is a graphical representation of a vector on a 2D plane. Many times, you will see a vector written as a column vector also. See below:

Column Vector

The top number shows us how many spaces to move on the x-axis and the bottom number shows us how many spaces to move on the y-axis.

Let’s actually write the code to draw vectors on a 2D Cartesian Plan Graph Grid. We will draw two vectors v and w:

Vector v and w
import numpy as np
import matplotlib.pyplot as plt

v = [2,4]
w = [4,2]

array = np.array([[0, 0, v[0], v[1]], 
                 [0, 0, w[0], w[1]]])

X, Y, V, W = zip(*array)
plt.figure()
plt.ylabel('Y-axis')
plt.xlabel('X-axis')
ax = plt.gca()
ax.annotate(f'v({v[0]},{v[1]})', (v[0],v[1]),fontsize=14)
plt.scatter(v[0],v[1], s=10,c='red')
ax.annotate(f'w({w[0]},{w[1]})', (w[0],w[1]),fontsize=14)
plt.scatter(w[0], w[1], s=10,c='blue')
ax.quiver(X, Y, V, W, angles='xy', scale_units='xy',color=['r','b'],scale=1)
ax.set_xlim([0, 10])
ax.set_ylim([0, 10])

plt.grid()
plt.draw()
plt.show()

Let’s explain what’s going on here:

  1. First, import numpy and matplotlib.pyplot libraries. If you don’t have them installed run the following code in your terminal.
    1. pip install matplotlib
    2. pip install numpy
  2. We define our two 2D vectors v and w. These are simple arrays.
  3. We define a numpy array. This array has two elements which are also arrays with 4 members each; one for vector v and another for vector w. We have four members for each element of this numpy array because of the quiver() function which we will explain shortly.
  4. We call zip() on our numpy array to create 4 new arrays X,Y,V and W. X and Y define the arrow locations and V,W define the arrow directions. This will be needed for the quiver() method. Recall that zip converts a list of iterables into tuples.
  5. plt.figure() holds all the plot elements.
  6. plt.ylabel and plt.xlabel methods label the y and x axis.
  7. The plt.gca() method returns the current axes to ax.
  8. ax.annotate() method adds labels to the end of the vector line, near the arrowhead.
  9. plt.scatter() method adds a small color point or dot at the end of the vector line, exactly where the arrowhead ends.
  10. ax.quiver() method plots our 2D arrows. It accepts the previously defined X, Y, V and W along with a few other parameters. The angles=’xy’, scale_units=’xy’, scale=1 parameters together allow us to plot vectors on the x-y plane. The color[] parameter array allows us to customize the color of the vector lines.
  11. ax.set_xlim() and ax.set_ylim() set the x and y axis view limits. In this case 10 is the limit of the view on each axis.
  12. plt.grid() adds a grid of lines to the plot.
  13. plt.draw() and plt.show() allow us to show the plot on the screen.

When we execute the code we get the following:

python plot vector matplotlib
v and w vector graph plot with gridlines

Thanks for reading. We hope this helped! Find the Python Notebook HERE. 👌👌👌

Tags: graphlinear algebramatplotlibvector
Previous Post

Python sqlite3 Delete Row

Next Post

Add and Subtract Vectors In Python

Khaleel O.

Khaleel O.

I love to share, educate and help developers. I have 14+ years experience in IT. Currently transitioning from Systems Administration to DevOps. Avid reader, intellectual and dreamer. Enter Freely, Go safely, And leave something of the happiness you bring.

Related Posts

Python

Python Fibonacci Recursive Solution

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Fibonacci Recursive Solution. Let's go! 🔥🔥🔥 The Fibonacci sequence is a series of numbers in which...

Read moreDetails
Python

Python Slice String List Tuple

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Slice string list tuple how-to tutorial. Let's go! 🔥🔥🔥 In Python, a slice is a feature...

Read moreDetails
Python

Python Blowfish Encryption Example

by Khaleel O.
January 14, 2024
0
0

Let's do a Python Blowfish Encryption example. Let's go! 🔥 🔥 Blowfish is a symmetric-key block cipher algorithm designed for...

Read moreDetails
Python

Python Deque Methods

by Khaleel O.
January 14, 2024
0
0

In this post we'll list Python Deque Methods. Ready? Let's go! 🔥🔥🔥 A deque (double-ended queue) in Python is a...

Read moreDetails

DevRescue © 2021 All Rights Reserved. Privacy Policy. Cookie Policy

Manage your privacy

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
Manage your privacy
To provide the best experiences, DevRescue.com will use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
No Result
View All Result
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us

DevRescue © 2022 All Rights Reserved Privacy Policy