Different Detailed example of Matplotlib python libraray

Basic Example of plotting Graph

Here is the basic example of generating a simple graph; the program is following:

from matplotlib import pyplot as plt  
#ploting our canvas  
plt.plot([1,2,3],[4,5,1])  
#display the graph  
plt.show()  

Output:

Basic Example of plotting Graph

It takes only three lines to plot a simple graph using the Python matplotlib. We can add titles, labels to our chart which are created by Python matplotlib library to make it more meaningful. The example is the following:

from matplotlib import pyplot as plt  
  
x = [5, 2, 7]  
y = [1, 10, 4]  
plt.plot(x, y)  
plt.title('Line graph')  
plt.ylabel('Y axis')  
plt.xlabel('X axis')  
plt.show()  

Output:

Basic Example of plotting Graph

The graph is more understandable from the previous graph.

Working with Pyplot

The matplotlib.pyplot is the collection command style functions that make matplotlib feel like working with MATLAB. The pyplot functions are used to make some changes to figure such as create a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot including labels, etc.

It is good to use when we want to plot something quickly without instantiating any figure or Axes.

While working with matplotlib.pyplot , some states are stored across function calls so that it keeps track of the things like current figure and plotting area, and these plotting functions are directed to the current axes.

The pyplot module provide the plot() function which is frequently use to plot a graph. Let’s have a look on the simple example:

from matplotlib import pyplot as plt  
plt.plot([1,2,3,4,5])  
plt.ylabel("y axis")  
plt.xlabel('x axis')  
plt.show()  

Output:

Working with Pyplot

In the above program, it plots the graph x-axis ranges from 0-4 and the y-axis from 1-5. If we provide a single list to the plot(), matplotlib assumes it is a sequence of y values, and automatically generates the x values. Since we know that python index starts at 0, the default x vector has the same length as y but starts at 0. Hence the x data are [0, 1, 2, 3, 4].

We can pass the arbitrary number of arguments to the plot(). For example, to plot x versus y, we can do this following way:

from matplotlib import pyplot as plt  
plt.plot([1,2,3,4,5],[1,4,9,16,25])  
plt.ylabel("y axis")  
plt.xlabel('x axis')  
plt.show()  

Output:

Working with Pyplot

Formatting the style of the plot

There is an optional third argument, which is a format string that indicates the color and line type of the plot. The default format string is ’ b- 'which is the solid blue as you can observe in the above plotted graph. Let’s consider the following example where we plot the graph with the red circle.

from matplotlib import pyplot as plt  
plt.plot([1, 2, 3, 4,5], [1, 4, 9, 16,25], 'ro')  
plt.axis([0, 6, 0, 20])  
plt.show()  

Output:

Working with Pyplot

Example format String

‘b’ Using for the blue marker with default shape.
‘ro’ Red circle
‘-g’ Green solid line
‘–’ A dashed line with the default color
‘^k:’ Black triangle up markers connected by a dotted line

The matplotlib supports the following color abbreviation:

Character Color
‘b’ Blue
‘g’ Green
‘r’ Red
‘c’ Cyan
‘m’ Magenta
‘y’ Yellow
‘k’ Black
‘w’ White

Plotting with categorical variables

Matplotlib allows us to pass categorical variables directly to many plotting functions: consider the following example

from matplotlib import pyplot  
names = ['Abhishek', 'Himanshu', 'Devansh']  
marks= [87,50,98]  
  
plt.figure(figsize=(9,3))  
  
plt.subplot(131)  
plt.bar(names, marks)  
plt.subplot(132)  
plt.scatter(names, marks)  
plt.subplot(133)  
plt.plot(names, marks)  
plt.suptitle('Categorical Plotting')  
plt.show()  

Output:

Working with Pyplot

In the above program, we have plotted the categorical graph using the subplot() function. Let’s a have a look on the subplot() function.

What is subplot()

The Matplotlib subplot() function is defined as to plot two or more plots in one figure. We can use this method to separate two graphs which plotted in the same axis Matplotlib supports all kinds of subplots, including 2x1 vertical, 2x1 horizontal, or a 2x2 grid.

It accepts the three arguments: they are nrows, ncols, and index . It denote the number of rows, number of columns and the index.

The subplot() function can be called in the following way:

subplot(nrows,ncols,index,**kwargs)  
subplot(pos,**kwargs)     
subplot(ax)

Parameters:

  • *args:

Three separate integers or three-digit integer describes the position of the subplot. If the three integers are nrows, ncols, and index in order, the subplot will take the index position on a grid with nrows row and ncol column .

The argument pos are a three-digit integer, where the first digit is denoted the number of rows, the second digit denoted the number of columns, and the third represents the index of the subplot. For example, subplot (1, 3, 2) is the same as the subplot (132).

Note: Passed integer must be less than 10.

  • **kwargs

The subplot() function also accepts the keyword arguments for the returned axes base class.