Matplotlib Tutorial
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

Matplotlib - Object-oriented API



At its core, Matplotlib is object-oriented. Matplotlib recommend directly working with the objects as it gives more control and customization of the plots. In object-oriented interface, a Figure can be divided into two different objects:

  • Figure object
  • Axes object

A Figure object can contain one or more axes objects. One axes represents one plot inside figure.

Creating plot using Object-oriented API

Before using any matplotlib.pyplot function, first of all the Pyplot module is imported from Matplotlib as shown below:

import matplotlib.pyplot as plt

After importing the module, all functions inside Pyplot module can be used in the current script.

Example: Simple plot

Consider the example below where plot() function is used to plot y = sin(x). After that, the axes functions are used to format the axes. At last, show() function is used to display the figure.

import matplotlib.pyplot as plt
import numpy as np

#creating a array of values between
#0 to 10 with a difference of 0.1
x = np.arange(0, 10, 0.1)
y = np.sin(x)

#creating figure and axes objects
fig = plt.figure()
ax = fig.add_axes([0.15,0.1,0.8,0.8])

#formatting axes
ax.set_title("Sine wave")
ax.set_xlabel("x")
ax.set_ylabel("y = sin(x)")

#drawing the plot
ax.plot(x, y)

#displaying the figure
plt.show()

The output of the above code will be:

Pyplot

Example: Adding legend

The example below shows how to add two plots in a single figure.

import matplotlib.pyplot as plt
import numpy as np

#creating a array of values between
#0 to 10 with a difference of 0.1
x = np.arange(0, 10, 0.1)
y1 = np.sin(x)
y2 = np.cos(x)

#plotting curves
plt.plot(x, y1) 
plt.plot(x, y2) 

#formatting axes
plt.xlabel("x")
plt.ylabel("y")
plt.title("Sine vs Cosine") 

#adding legend
plt.legend(['sin(x)', 'cos(x)']) 

#displaying the figure
plt.show()

The output of the above code will be:

Pyplot

Format String

A format string consists of a part for color, marker and line:

fmt = '[marker][line][color]'

Each of them is optional. If not provided, the value from the style cycle is used. Other combinations such as [color][marker][line] are also supported, but note that their parsing may be ambiguous.

A format string can be added to a plot to add more styles in it.

Markers

CharacterDescription
'.' point marker
',' pixel marker
'o' circle marker
'v' triangle_down marker
'^' triangle_up marker
'<' triangle_left marker
'>' triangle_right marker
'1' tri_down marker
'2' tri_up marker
'3' tri_left marker
'4' tri_right marker
'8' octagon marker
's' square marker
'p' pentagon marker
'P' plus (filled) marker
'*' star marker
'h' hexagon1 marker
'H' hexagon2 marker
'+' plus marker
'x' x marker
'X' x (filled) marker
'D' diamond marker
'd' thin_diamond marker
'|' vline marker
'_' hline marker

Line styles

CharacterDescription
'-' solid line style
'--' dashed line style
'-.' dash-dot line style
':' dotted line style

Colors

CharacterDescription
'b' blue
'g' green
'r' red
'c' cyan
'm' magenta
'y' yellow
'k' black
'w' white

Example: Using format string

In the example below, format string is used to add more styles in the plot.

import matplotlib.pyplot as plt
import numpy as np

#creating a array of values between
#0 to 10 with a difference of 0.5
x = np.arange(0, 10, 0.5)
y1 = np.sin(x)
y2 = np.cos(x)

#plotting curves
plt.plot(x, y1, 'o-r') 
plt.plot(x, y2, 'v--b') 

#formatting axes
plt.xlabel("x")
plt.ylabel("y")
plt.title("Sine vs Cosine") 

#adding legend
plt.legend(['sin(x)', 'cos(x)']) 

#displaying the figure
plt.show()

The output of the above code will be:

Pyplot

5