MATPLOTLIB.

MATPLOTLIB:

Matplotlib is the one of the important libraries in python.
matplotlib.pyplot is a useful tool and is a collection of command style style function that makes matplotlib act as matlab.
To use the above tool we must import it first.
The Syntax is:

import matplotlib.pyplot as plt

In the above syntax we used 'as' to give an alias name to the tool we imported and the alias name is 'plt'

To plot a graph we use library.plot(parameters) i.e., from the above example plt.plot(parameters)

For example:

plt.plot([2,4,6,4])

In the above example, we have given only one array. If only one array is given take them as y co-ordinates in default i.e..,
The X values are :[0,1,2,3]
The Y values are :[2,4,6,4]
And the points plotted on graph G(x,y) is:[(0,2),(1,4),(2,6),(4,4)]

if we don't want the default values:

plt.plot([1,2,4,6],[4,7,8,9]) 

In the above example, the first array indicates the x co-ordinates and the second array indicates the y co-ordinates.
Here,
The X values are :[1,2,4,6]
The Y values are :[4,7,8,9]
And the points plotted on graph G(x,y) is:[(1,4),(2,7),(3,8),(4,9)]

X=[1,2,3,4]
Y=[2,3,4,5]
plt.plot(X,Y,linewidth=5)

In the above example the line in the graph will have the specified width

Other function in matplotlib library:

  1. plt.ylabel("string"): Used for naming y-axis
  2. plt.xlabel("string"): Used for naming x-axis
  3. plt.show()              : Used to display the graph as output.
  4. plt.title("string")    : Used for naming the graph i.e., giving a title to the graph.
  5. plt.grid()                : Used to display grid in graph(In default the grid is off).
  6. plt.legend()            : Used to show labels in graph in the top right corner. Legend function makes the graph extremely readable(understandable) and helpful when we have multiple lines in the graph.

Use of setp function:

#use keyword arguments

line=plt.plot(X,Y)
plt.setp(line,color="r",linewidth=2.5)
here r=red(i.e., represents colors)
we can even write full name of the color. This type of representation most suitable for CS/IT students.

#use matlab style string value

plt.setp(line,'color','r','linewidth',5)
This type of representation is most suitable for ECE students.

Work with multiple figures and axis:

plt.figure(figure no): Used to create new figure or graph.
plt.subplot((no.of rows)(no.of columns)(figure no:)): Used to split the graph into multiple subgraphs
For example:

plt.subplot(211)

In the above example, 211 means, 2 rows , 1 column in figure 1. which makes two subgraphs in vertical order.

Note: In all the above examples plt is the alias name for matplotlib.pyplot.

No comments:

Post a Comment