We are going to look at a few examples, and then I will provide the code to do create the plots through Google Colab!

Goals:

  1. Learn to create a vector array.
  2. Manipulate vector to match an equation.
  3. Create beautiful plots with a title, axis labels, and grid.

Let’s go ahead and start by working on one of the simplest and most common equations.

y = x2

To do this, we are going to be doing a few things but first of all, we will be using 2 modules: Matplotlib.pyplot and Numpy.

Numpy

It is a Python library that provides.
Is the fundamental package for scientific computing in Python.

  • A multidimensional array object.
  • Derived objects such as arrays and matrices.

and an assortment of routines for fast operations on arrays, including mathematical and logical:

  • Shape manipulation
  • Sorting
  • Selecting
  • Discrete Fourier Transforms
  • Basic linear algebra
  • Basic statistical operations
  • Random simulation
  • much more
Matplotlib.pyplot

Is a collection of command style functions that make matplotlib work like MATLAB.
Each pyplot function makes some change to a figure:

  • Creates a figure.
  • Plots some lines in a plotting area.
  • Decorates the plot with labels.
  • etc.
Creating an X and a Y vector

We want to plot from 0–10 on the x-axis, but let’s think about what each value would be:
x = [1,2,3,4,…,9,10]
y = [1,4,9,16,…,99,100]
In this case, every value in y is just the x value at the same index squared.
Now that we have all of these values, we can just put them into a python variable and plot!

  1. Import our modules that we are using.
    import matplotlib.pyplot as plt
    import numpy as np
    
  2. Create the vectors X and Y.
    x = np.array(range(10))
    y = x ** 2
    
  3. Create the plot
    plt.plot(x, y)
    

and then the resulting image:

I will go into a few options that we can add to make our plots look better!

  1. When plotting add a label for the legend.
  2. Adding a title.
  3. Add X and Y label.
  4. Add a grid with opacity of .9 and linestyle of ‘-‘.
  5. Show the legend.

Finally, you can add multiple plots to the same figure.


Link:1 matplotlib pyplot.ipynb

Deja un comentario