In a good pythonic style, matplotlib is an object oriented plotting library that can generate a variety of visualisations: From simple plots, histograms, bar charts, scatterplots and more with a few lines of code. If you are familiar with Matlab or Octave, you will find pylab very easy to use. Let us start by importing the modules.
import numpy as np
import matplotlib.pyplot as plt
from pylab import*
Let us create a simple figure to plot the following functions:
y 1 = x 2 y_1=x^2 y1=x2
y 2 = x 3 y_2=x^3 y2=x3
With the aid NumPy we can create a vector with entries for x x x and calculate y 1 y_1 y1 and y 2 y_2 y2:
x = np.linspace(-5, 5, 200)
y1 = x**2
y2 = x**3
We can create a plot using the plot command as follows:
fig, ax = plt.subplots()
ax.plot(x, y1, 'r', label=r"$y_1=x^2$", linewidth=2)
ax.plot(x, y2, 'k--', label=r"$y_2=x^3$", linewidth=2)
ax.legend(loc=2)
ax.set_xlabel(r'$x$', fontsize=18)
ax.set_ylabel(r'$y$', fontsize=18)
ax.set_title('My Figure')
plt.show()
Remember that matplotlib is an object oriented library and thus we are using objects to create our plots. The commands above are very similar to those used in Matlab and Octave and should you need to take a closer look at the syntax you can consult other resource. The result of the commands above can be seen in above. Finally, it is possible to save the plot to a file with a single command. In this case we can create a PNG file with the following line of code:
fig.savefig('firstplot.png')
reference
Data Science and Analytics with Pyhton by Jesus Rogel-Salazar