Python MatPlotLib – A quick reference

  1. matplotlib is a library in Python for plotting/visualizing the data
  2. Two approaches for creating plots – i) functional based methods ii) OOP based methods using FIGURE object
  3. Figure object helps you in movig the axes within the same canvas, thus allowing to have multiple plots in a single canvas
  4. Main lib –
  5. Aabhar : Jose Portilla (Head of Data Science at Pierian Training) @Udemy
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,10)
y = x * 2   #np.log(x)

plt.xlabel('My X Axes')
plt.ylabel("My Y Axes")
plt.title("Sample Plot")
plt.ylim(0,15)  # lim allows to shrink and fit the ploat within provided value - you may loosed the graph here # If you run the script as python code not as jupyter-notebook, this is needed
# Using conventional functional method of saving fig using savefig() method
#plt.savefig('D:\\DataScienceLearning\\PythonPrograms\\RK_PGMS\\myimage.png', dpi=100.0)

figObj = plt.figure()
# RES -> <class 'matplotlib.figure.Figure'>
# Below creates a canvas for ratio for LEFT, BOTTOM, WIDTH, HEIGHT -> [(x,y),(w,h)]
figObj.add_axes([0,0,1,1]) # there numbers are basically a ratio number
figObj2 = plt.figure()
myAxes_A = figObj2.add_axes([0,0,1,1]) # This will occupy just half the canvas - This has notthing to do with the actual data points
myAxes_B = figObj2.add_axes([0.25,0.25,0.125,0.125]) # 1/4th and 1/8th
# Let us add multiple plots within the same figure

myAxes_A.plot(np.linspace(0,5,6), np.linspace(0,5,6)**4)
myAxes_B.plot(x,y)  #Subplot with smaller window

# PUTTING LEGENDS, linewidth, linestyle, marker

fig = plt.figure()
ax= fig.add_axes([0,0,1,1],title='MyGraph', xlabel='X Axes', ylabel='Y Axes')
myXSets = np.linspace(0,10,10)
myYSets_1 = myXSets
myYSets_2 = myXSets**2
ax.plot(myXSets, myYSets_1, label="Set1",  color='purple', marker='o', markersize=10)
ax.plot(myXSets, myYSets_2, label="Set2", marker = '+', linewidth = 10, linestyle='--', markeredgecolor='red') #Line width/style
# Set your legends to a location with loc value or number
ax.legend(loc='center left')   # best-0,upper right-1, upper left-2, lower left-3, lower right-4, right = 5...
# You can set as per convas