0% found this document useful (0 votes)
10 views21 pages

Matplotlib Data Visualization Guide

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views21 pages

Matplotlib Data Visualization Guide

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

Matplotlib:

----------
Introduction to Matplotlib:
---------------------------
Numpy--->Data Analysis library
Pandas--->Data Analysis library/Data Visualization
Matplotlib/Seaborn/plotly--->Data visualization libraries

Need of data visualization:


---------------------------
represent data in visual format.

identity function
square function
cube function

x---->x
x---->x**2
x---->x**3

import [Link] as plt


import numpy as np
x = [Link](1,11)
i=x
s=x**2
c =x**3
[Link](x,i,marker='o')
[Link](x,s,marker='o')
[Link](x,c,marker='o')
[Link]()

From line plot, we can identify the growth of cubic function is very high, when
compared with square and identity functions.

Advantages:
We can identify relationships very easily.
We can identify differences very easily.
We can identify patterns so that we can do predictions very easily.

To visualize data, multiple visualization libraries are available in pythonn


1. Matplotlib
2. Seaborn
3. Plotly
etc..

1. Matplotlib Introduction:
---------------------------
1. most popular and oldest visualization library.
Python's alternative to MATLAB.

2. It is freeware and open source.

3. 2-D graphs and 3-D graphs


4. static graphs,interactive visualizations,animations

5. Jhon Hunter on top of numpy and sidePy libraries

6. All advanced python's data visualization libraries are depends on matplotlib.


7. Very large community support is there.

8. official website: [Link]


Examples tab--->source code for every graph available

How to install matplotlib:


--------------------------
2 ways

1st way:
--------
With anaconda distribution automatically, matplotlib is available.

conda install matplotlib

2nd way:
--------

pip install numpy


pip install matplotlib
pip install seaborn
pip install pandas

How to check installation:


--------------------------
>>> import matplotlib
>>> matplotlib.__version__
'3.4.2'

1. Need of Data Visualization


2. Matplotlib introduction
3. How to install matplotlib

1. Types of plots:
-----------------
Several types of plots/graphs are supported by matplotlib.
The main important are:

1. Line plots
2. Bar charts
3. Pie charts
4. Histograms
5. Scatter plots
etc

Based on our requirement and available input data, we can choose corresponding
plot/graph.

matplotlib library contains pyplot module


pyplot module defines several functions to plot data in visual form.

1. plot()
2. bar()
3. pie()
4. hist()
5. scatter()
etc

We can create plots in 2 approaches:

1. Functional way/procedural way(pyplot)


For small data sets

2. Object Oriented way


Larger data sets

Telegram Link for discussions: [Link]

1. Line Plot:
-------------
We can mark data points from the input data and we can connect these data points
with lines , such type of plots are called line plots

It is very helpful to find relationships between two data sets.

pyplot module contains plot() function to create line plot.

plot(*args, scalex=True, scaley=True, data=None, **kwargs)

*args--->any number of arguments


**kwargs--->any number of keyword arguments

Creation of Line plot by passing 2 ndarrays:


--------------------------------------------
Square function behaviour

import [Link] as plt


import numpy as np
a = [Link](1,11)
b = a**2
[Link](a,b) # the values from a for x-axis and values from b for y-axis
[Link]()

[Link]()
[Link]()

What is figure:
---------------
Figure is an individual window on the screen, in which matplotlib displays our
graphs. ie It is a container for our graphical output.

plot() function itself is responsible to create figure object.

How to add title to the line plot:


----------------------------------
Title describes the information about our graph

[Link]('Square Values Line Plot')

How to add xlabel and ylabel to the line plot:


----------------------------------------------

[Link]('Input Number')
[Link]('Square Value')

import [Link] as plt


import numpy as np
a = [Link](1,11)
b = a**2
[Link](a,b) # the values from a for x-axis and values from b for y-axis
[Link]('Square Values Line Plot')
[Link]('Input Number')
[Link]('Square Value')
[Link]()

[Link](a,b)
[Link]('title')
[Link]('label for x-axis')
[Link]('label for y-axis')
[Link]()

Line Plots Advanced Properties:


-------------------------------
1. Line Properties:
-------------------
A line drawn on the graph has several properties like
color,style,width,transparency etc
Based on our requirement, we can customize these properties.

1. Marker property:
-------------------
We can use marker property to highlight data points on the line plot.
By using marker keyword argument, we can set marker.
[Link](a,b,marker='o')

**Markers**

============= ===============================
character description
============= ===============================
``'.'`` 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
============= ===============================

2. Line style property:


----------------------
It specifies whether the line is solid, dashed , dotted line etc
linestyle keyword argument

- --------> solid line


-- --------> dashed line
: --->dotted line
-. ------>dash-dot line

**Line Styles**

============= ===============================
character description
============= ===============================
``'-'`` solid line style
``'--'`` dashed line style
``'-.'`` dash-dot line style
``':'`` dotted line style
============= ===============================

3. color property:
------------------
We can specify our own required color.
By using color keyword argument.
We can use any color even hexacode

predefined single letter color codes:

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

Default color:
--------------
The default first color is blue.
The default second color is orange color.
The default third color is green color.
The default fourth color is red color.

[Link]['axes.prop_cycle'].by_key()

>>> [Link]['axes.prop_cycle'].by_key()
{'color': ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b',
'#e377c2', '#7f7f7f', '#bcbd22', '#17becf']}

marker
linestyle
color

Shortcut way to set marker,linestyle,color properties:


------------------------------------------------------
By using formatted string

We can specify: either mlc or cml

'o-r' or 'ro-'

We are not required to specify all three. Based on our requirement we can provide 1
or 2 or 3 arguments.

import [Link] as plt


import numpy as np
a = [Link](1,11) #[1,2,3,4,5,..10]
b = a**2 #[1,4,9,16,25...]
[Link](a,a**2,'m^--') #mlc or cml
[Link]('Square Function Line Plot')
[Link]('Input Value')
[Link]('Square Value')
[Link]()

[Link](a,a**2,'mo')
[Link](a,a**2,'o:')
[Link](a,a**2,'r')

[Link]

markeredgecolor or mec any matplotlib color


markeredgewidth or mew float value in points
markerfacecolor or mfc any matplotlib color
markerfacecoloralt or mfcalt any matplotlib color
markersize or ms float

linewidth or lw float value in points

%matplotlib inline
import [Link] as plt
import numpy as np
a = [Link](1,11) #[1,2,3,4,5,..10]
b = a**2 #[1,4,9,16,25...]
[Link](a,a**2,color='red',lw=10,marker='o',mew=15,mec='g')
[Link]('Square Function Line Plot')
[Link]('Input Value')
[Link]('Square Value')
[Link]()

Components of Line Plot:


------------------------
diagram

Sequence of activities of plot() function:


------------------------------------------
1. Creation of figure object
2. creation of plot object/axes
3. Draw and x and y axis.
4. Mark evenly spaced scales(ticks) on the axes ie x-axis and y-axis
5. Plot data points
6. connect data points with line
7. add title, xlabel and ylabel

For Jupiter Notebook:


%matplotlib inline

Line properties
Marker property
linestyle property
color property
shortcut way fmt string(cml or mlc)
default colors
components of line plot
sequence of activities of plot() function

How to customize the size of figure:


------------------------------------
Default size: 8 inches width and 6 inches height.
We can customize this size by using figure() function

figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None,


frameon=True, FigureClass=<class '[Link]'>, clear=False,
**kwargs)
Create a new figure, or activate an existing figure.

import [Link] as plt


import numpy as np
a = [Link](1,11) #[1,2,3,4,5,..10]
b = a**2 #[1,4,9,16,25...]
[Link](num=1,figsize=(4,4),facecolor='g')
[Link](a,a**2,'ro-')
[Link]('Square Function Line Plot')
[Link]('Input Value')
[Link]('Square Value')
[Link]()

How to save line plot to a file:


--------------------------------
[Link]('[Link]')

import [Link] as plt


import numpy as np
a = [Link](1,11) #[1,2,3,4,5,..10]
b = a**2 #[1,4,9,16,25...]
[Link](num=1,figsize=(5,5),edgecolor='y')
[Link](a,a**2,'ro-')
[Link]('Square Function Line Plot')
[Link]('Input Value')
[Link]('Square Value')
[Link]('[Link]')
[Link]()

We can specify any location, but we have to use absolute path(full path)
[Link]('C:\\Users\\lenovo\\Desktop\\[Link]')

Creation of line plot by passing a single array:


------------------------------------------------
That single array will be considered for y-axis.
The x-axis values will be generated automatically by matplotlib with values from 0
to N-1
a= [10,20,30,40]
[Link](a)
The data points are: (0,10),(1,20),(2,30),(3,40)

import [Link] as plt


import numpy as np
a = [Link]([10,20,30,40,50])
[Link](a,'o-r')
[Link]()

Multiple plots on the same graph:


---------------------------------
We can plot any number of line plots on the same graph.
This approach is helpful for comparison purposes.

import [Link] as plt


import numpy as np
x = [Link](1,11)
i = x
s = x**2
c = x**3
[Link](x,i,'o-r')
[Link](x,s,'o-b')
[Link](x,c,'o-g')
[Link]('One Graph, But Multiple Plots')
[Link]()

Shortcut way:
-------------
We can use single plot() function instead of multiple plot() functions

[Link](x,i,'o-r',x,s,'o-b',x,c,'o-g')

import [Link] as plt


import numpy as np
x = [Link](1,11)
i = x
s = x**2
c = x**3
[Link](x,i,'o-r',x,s,'o-b',x,c,'o-g')
[Link]('One Graph, But 3 Lines')
[Link]()

If we pass any keyword arguments, those are appliacble for all plots.
[Link](x,i,'o-r',x,s,'o-b',x,c,'o-g',lw=10,maker='+')

For First line: x,i,'o-r'


For Second line: x,s,'o-b'
For Third line: x,c,'o-g'
maker '+' will be applicable for all 3 lines(old values will be overridden)
But linewidth property is applicable for all lines.
If any conflict in the properties then keyword argument property will get more
priority.

x=10
x=20
x=30
x=40

How to customize title properties:


----------------------------------
[Link]('my title')

title(label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs)


Set a title for the Axes.

label : str
Text to use for the title

fontdict : dict
A dictionary controlling the appearance of the title text,

loc: location of title. The allowed values are: {'center', 'left', 'right'}
pad: The offset(space) of the title from the top of the axes.
**kwargs--->To customize font properties

The allowed fontstyle or style are:


'normal','italic','oblique'

The allowed values for fontweight: 0 to 1000

'fontfamily' or 'family': 'serif','cursive','fantasy','monospace'

import [Link] as plt


import numpy as np
a = [Link](1,11)
b = a**2
[Link](a,b,'o-r')
[Link]('Square Values Plot',
{'color':'red','size':20,'backgroundcolor':'yellow','alpha':1.0,'fontstyle':'italic
','fontweight':1000,'fontfamily':'fantasy','rotation':180},pad=25)
[Link]()

[Link]

How to customize x-lable and y-label properties:


------------------------------------------------
xlabel(xlabel, fontdict=None, labelpad=None, *, loc=None, **kwargs)
Set the label for the x-axis.

ylabel(ylabel, fontdict=None, labelpad=None, *, loc=None, **kwargs)


Set the label for the y-axis.

import [Link] as plt


import numpy as np
a = [Link](1,11)
b = a**2
[Link](a,b,'o-r')
[Link]('input values',
{'color':'red','size':15,'backgroundcolor':'yellow','rotation':10,'alpha':0.9})
[Link]('Square
values',color='red',size=15,backgroundcolor='yellow',rotation=30,alpha=0.3)
[Link]()

check as many properties as possible from


[Link]

Chapter-1: Introduction to Matplotlib


1.1. Need of Data Visualization
1.2. Matplotlib Introduction
1.3. Installing Matplotlib
Chapter-2: Line Plots-Basics
2.1. Types of plots
2.2. Line Plots
2.3. Creation of Line Plot by passing 2 ndararys
2.4. What is Figure?
2.5. How to add title to the line plot
2.6. How to add xlabel and ylabel to the line plot
Chapter-3: Line Plots-Advanced
3.1. Line Properties
3.1.1. Marker Property
3.1.2. Linestyle Property
3.1.3. Color property
3.1.4. Default Color
3.1.5. Shortcut way to set color,marker and linestyle
3.2. Components of Line Plot
3.3. Sequence of activities of plot() function
3.4. How to customize the size of figure
3.5. How to save line plot to a file
3.6. Creation of line plot by passing a single array
3.7. Multiple plots on the same Graph
3.8. How to customize title Properties
3.9. Customization of xlabel and ylabel

Chapter-4: How to add grid() lines to the plot:


-----------------------------------------------
We can add grid lines to the plot. For this we have to use grid() function.

Syntax:
-------
Help on function grid in module [Link]:

grid(b=None, which='major', axis='both', **kwargs)


Configure the grid lines.

b : bool or None, optional


Whether to show the grid lines. If any *kwargs* are supplied,
it is assumed you want the grid on and *b* will be set to True.

If *b* is *None* and there are no *kwargs*, this toggles the


visibility of the lines.

[Link]() #visible
[Link]() #hide
[Link]() #visible

import [Link] as plt


import numpy as np
a = [Link](1,11)
b = a**2
[Link](a,b,'o-r')
[Link]('input value')
[Link]('Square value')
[Link]('Square Function')
[Link]()
[Link]()

various cases:
--------------
case-1:
--------
[Link](a,b,'o-r')
[Link]()
[Link]()

In this case grid will be displayed.


case-2:
-------
[Link](a,b,'o-r')
[Link]() #visible
[Link]() #hide
[Link]() #visible
[Link]() #hide
[Link]()

toggling will be happend.

case-3:
-------
[Link](a,b,'o-r')
[Link]()
[Link](color='green')
[Link]()

grid will be displayed because we are passing keyword arguments.

case-4:
-------
[Link](b=True) # to display grid lines
[Link](b=False) # to hide grid lines

which property:
--------------
major lines and minor lines
By using which property we can specify which grid lines have to display.
The allowed values for which property: major,minor,both

import [Link] as plt


import numpy as np
a = [Link]([10,20,30,40,50])
[Link](a,a,'o-r')
plt.minorticks_on()
[Link](which='both')
[Link]()

Note:
minorticks_on()
Display minor ticks on the axes.

Displaying minor ticks may reduce performance; you may turn them off
using `minorticks_off()` if drawing speed is a problem.

eg:
import [Link] as plt
import numpy as np
a = [Link]([10,20,30,40,50])
[Link](a,a,'o-b',lw=7,markersize=10,markerfacecolor='yellow')
plt.minorticks_on()
[Link](which='minor',color='green')
[Link](color='red',lw=5)
[Link]()

axis property:
--------------
It decides on which axis, grid lines have to display.
Allowed values are 'x','y','both'
default value is : both

[Link](axis='x') --->grid lines will be displayed only on x-axis


[Link](axis='y')--->grid lines will be displayed only on y-axis
[Link](axis='both')--->grid lines will be displayed on both x-axis and y-axis

Note: we can use several keyword arguments also


import [Link] as plt
import numpy as np
a = [Link]([10,20,30,40,50])
[Link](a,a,'o-r')
[Link](color='g',linestyle=':',linewidth=2)
[Link]()

Chapter-4: How to add grid lines to plot


4.1. Syntax and First Example with Grid
4.2 Various cases of grid() function usage
4.3 which property
4.4 Example To find much difference between major and minor grid lines
4.5. axis property

Adding Legend:
--------------
If multiple lines present in our plot, then it is difficult to identify which line
represents which function.

To overcome this problem we should add legend to the line plot.


Legend is a box associating text labels with lines on the graph.

By using legend() function, we can add legend to the plot.


legend(*args, **kwargs)
Place a legend on the Axes.

Call signatures::

legend()
legend(labels)
legend(handles, labels)

1. legend():
------------
If we are not passing any arguments,then the elements to be added to the legend are
automatically considered based on order of lines creation.
The labels will be considered from the plot() function argument.

import [Link] as plt


import numpy as np
a = [Link](1,6)
[Link](a,a,'o-r',label='a')
[Link](a,a**2,'o-b',label='a**2')
[Link](a,a**3,'o-g',label='a**3')
[Link]()
[Link]()

eg-2:
import [Link] as plt
import numpy as np
a = [Link](1,6)
[Link](a,a,'o-r',label='a')
[Link](a,a**2,'o-b',label='a**2')
[Link](a,a**3,'+:c',label='a**3')
[Link]()
[Link]()

2. legend(labels)
-----------------
The argument is list of strings.
Each string is considered as a label for the plots, in order they created.

[Link](['label-1','label-2','label-3'])

This approach is best suitable for adding legend for already existing plots.

import [Link] as plt


import numpy as np
a = [Link](1,6)
[Link](a,a,'o-r')
[Link](a,a**2,'o-b')
[Link](a,a**3,'+:c')
[Link](['label-1','label-2','label-3'])
[Link]()

Note: This approach is not recommended because we should aware the order in which
the plots were created.

3. legend(handles, labels)
---------------------------
We can define explicity handles and labels in the legend function itself.
This approach is highly recommended because complete control is there.

l = [10]
a,= l #unpacking of list
print(a)

eg-1:
import [Link] as plt
import numpy as np
a = [Link](1,6)
line1, = [Link](a,a,'o-r')
line2, = [Link](a,a**2,'o-b')
line3, = [Link](a,a**3,'o-g')
[Link]([line3,line1,line2],['cube','ident','sqr'])
[Link]()

eg-2:
import [Link] as plt
import numpy as np
a = [Link](1,6)
handles = [Link](a,a,'o-r',a,a**2,'o-b',a,a**3,'o-g')
[Link](handles,['identity','square','cube'])
[Link]()

legend()
legend(labels)
legend(handles, labels)

How to adjust legend location:


------------------------------
Based on our requirement, we can decide legend location in the plot. For this we
have to use loc argument.

loc -->location

=============== =============
Location String Location Code
=============== =============
'best' 0
'upper right' 1
'upper left' 2
'lower left' 3
'lower right' 4
'right' 5
'center left' 6
'center right' 7
'lower center' 8
'upper center' 9
'center' 10

import [Link] as plt


import numpy as np
a = [Link](1,6)
handles = [Link](a,a,'o-r',a,a**2,'o-b',a,a**3,'o-g')
[Link](handles,['identity','square','cube'],loc=4)
[Link]()

How to specify number of columns in the legend:


-----------------------------------------------
Bydefault number of columns is 1.
But we can customize number of columns based on our requirement. For this we have
to use ncol argument.

ncol : int, default: 1


The number of columns that the legend has.

import [Link] as plt


import numpy as np
a = [Link](1,6)
handles = [Link](a,a,'o-r',a,a**2,'o-b',a,a**3,'o-g')
[Link](handles,['identity','square','cube'],ncol=3)
[Link]()

[Link](handles,['identity','square','cube'],ncol=3,title='3 different
functions')

Note: we can do more customizations like


1. We can configure title
2. We can change look and feel
3. We can change font size and color
4. We can place legend outside of the plot
5. We can define multiple legends in a single plot
etc

Customization of Tick Location and Labels:


-------------------------------------------
Ticks are the markers to represent specific value on the axis.
Ticks are very helpful to locate data points on the plot very easily.
Based on input range, ticks will be generated automatically by matplotlib itself.
But based on our requirement, we can customize tick values and corresponding labels
also. For this we have to use
xticks() and yticks() functions.

Syntax:
------
xticks(ticks=None, labels=None, **kwargs)
Get or set the current tick locations and labels of the x-axis.
Pass no arguments to return the current values without modifying them.

The same function acts as both getter and setter function.


If we are not passing any argument then it acts as getter function.
xticks()--->getter function
xticks(data)--->setter function

yticks(ticks=None, labels=None, **kwargs)


Get or set the current tick locations and labels of the y-axis.

import [Link] as plt


import numpy as np
a = [Link](11) # 0 to 10
b = a*100 # 0 to 1000
[Link](a,b,'o-r')
[Link]('Sales Report')
[Link]('Year')
[Link]('Number of Sales')
[Link]()
[Link]()

The default tick values generated by matplotlib are:

xticks: 0,2,4,6,8,10
yticks: 0,200,400,600,800,1000

To customize our own xticks and labels:


---------------------------------------
#[Link]([0,1,2,3,4,5,6,7,8,9,10])
#[Link](ticks=[0,1,2,3,4,5,6,7,8,9,10])
#[Link](ticks=a)
#[Link](a)

For these tick values, we can configure our own labels also.
[Link](ticks=a,labels=['2000','2001','2002','2003','2004','2005','2006','2007',
'2008','2009','2010'])

We can use keyword arguments to customize label properties like color, size etc
import [Link] as plt
import numpy as np
a = [Link](11) # 0 to 10
b = a*100 # 0 to 1000
[Link](a,b,'o-r')
[Link]('Sales Report')
[Link]('Year')
[Link]('Number of Sales')
[Link]()
#[Link]([0,1,2,3,4,5,6,7,8,9,10])
#[Link](ticks=[0,1,2,3,4,5,6,7,8,9,10])
#[Link](ticks=a)
[Link](ticks=a,labels=['2000','2001','2002','2003','2004','2005','2006','2007',
'2008','2009','2010'],color='blue',size=15,rotation=30)
[Link]()

Similarly we can customize yticks also.


import [Link] as plt
import numpy as np
a = [Link](11) # 0 to 10
b = a*100 # 0 to 1000
[Link](a,b,'o-r')
[Link]('Sales Report')
[Link]('Year')
[Link]('Number of Sales')
[Link]()
#[Link]([0,1,2,3,4,5,6,7,8,9,10])
#[Link](ticks=[0,1,2,3,4,5,6,7,8,9,10])
#[Link](ticks=a)
[Link](ticks=a,labels=['2000','2001','2002','2003','2004','2005','2006','2007',
'2008','2009','2010'],color='blue',size=15,rotation=30)
[Link](ticks=[0,250,500,750,1000],labels=['zero','250','500','750','1000'],colo
r='green',size=10,rotation=90)
[Link]()

Note:
1. without providing tick values, we cannot provide labels, otherwise we will get
error.
eg:
[Link](labels=['2000','2001','2002','2003','2004','2005','2006','2007','2008','
2009','2010'],color='blue',size=15,rotation=30)
TypeError: xticks(): Parameter 'labels' can't be set without setting 'ticks'

2. If we pass empty list to ticks then tick values will become invisible.

sir does it mean, labels are for human understanding and ticks are for python
understanding?

import [Link] as plt


import numpy as np
a = [Link](11) # 0 to 10
b = a*100 # 0 to 1000
[Link](a,b,'o-r')
[Link]('Sales Report')
[Link]('Year')
[Link]('Number of Sales')
[Link]()
[Link](ticks=a)
[Link](ticks=b)
[Link]()

How to set limit for range of values on x-axis and y-axis?


----------------------------------------------------------
import [Link] as plt
import numpy as np
x = [Link](1,101) # 1 to 100
y = x**2 # 1 to 10000
[Link](x,y,'o-r')
[Link]()
[Link]()

In this plot, left and right values on x-axis , top and bottom values on y-axis are
decided by matplotlib itself based on input values range.

We can customize this range of values by using xlim() and ylim() functions.
xlim(*args, **kwargs)
Get or set the x limits of the current axes.

Call signatures::

left, right = xlim() # return the current xlim


xlim((left, right)) # set the xlim to left, right
xlim(left, right) # set the xlim to left, right

If we are not passing any arguments, then this function acts as getter function. It
returns left and right limits on the x-axis.

If we are passing any arguments, then this function acts as setter function. It
sets left and right limits on x-axis.

Getting left and right limits on x-axis:


----------------------------------------
import [Link] as plt
import numpy as np
x = [Link](1,101)
y = x**2
[Link](x,y,'o-r')
[Link]()
left,right = [Link]()
print('Left Limit on x-axis:',left)
print('Rigth Limit on x-axis:',right)
[Link]()

D:\durgaclasses>py [Link]
Left Limit on x-axis: -3.95
Rigth Limit on x-axis: 104.95

To set left and right limits on x-axis:


---------------------------------------
import [Link] as plt
import numpy as np
x = [Link](1,101)
y = x**2
[Link](x,y,'o-r')
[Link]()
[Link](1,50)
[Link]([1,10,20,30,40,50])
[Link]()

various possible syntaxes to set left and right limits on x-axis:


------------------------------------------------------------------
1. xlim(left,right)
2. xlim((left,right))
3. xlim(right=50) #left value will be generated by matplotlib
4. xlim(left=1) #right limit will be generated by matplotlib
5. xlim(v) #v will be considered as left limit value. default value for right limit

Note: The following 2 lines meant for same functionality


xlim(left=v)
xlim(v)

ylim():
-------
exactly same as xlim() except that it is meant for limiting range of values on y-
axis.

ylim(*args,*kwargs)

Various possible call signatures:


---------------------------------
1. bottom,top = [Link]() #getter function
2. [Link](100,2500) #bottom is 100 and top is 2500
3. [Link](bottom=100) #bottom is 100 and top is default value
4. [Link](top=2500) #top is 2500 and bottom is default
5. [Link](2500) #bottom 2500 and top is default value

import [Link] as plt


import numpy as np
x = [Link](1,101)
y = x**2
[Link](x,y,'o-r')
[Link]()
[Link](100,2500)
[Link]()

How to customize tick values on x-axis and y-axis.


How to customize limits on x-axis and y-axis?

How to set scale of x-axis and y-axis?


--------------------------------------
The difference between any two consecutive points on any axis is called scaling.

The most commonly used scales in matplotlib are:


1. Linear Scaling
2. Logarithmic Scaling

1. Linear Scaling:
------------------
The difference between any two consecutive points is always fixed.
Bydefault matplotlib follows linear scaling.

If the data set values are spreaded over small range, then linear scaling is the
best choice.

eg: 0 20 40 60 80 100

2. Logarithmic Scaling
----------------------
The difference between any two consecutive points is not fixed and it is multiples
of 10, such type of scaling is called logarithmic scaling.

10^0 10^1 10^2 10^3 10^4

If the data set values are spreaded over big range, then logarithmic scaling is the
best choice.

We can set xscale and yscale by using the following functions

1. [Link](value,**kwargs)
set x-axis scale
2. [Link](value,**kwargs)
set y-axis scale

value : {"linear", "log", "symlog", "logit", ...}

To demonstrate linear and logarithmic scaling on x-axis:


--------------------------------------------------------
import [Link] as plt
import numpy as np
a = [Link](10000)
b = [Link](10000)
[Link](a,b,'o-r')
#[Link]('linear')
[Link]('log')
#[Link]('linear')
[Link]('log')
[Link]()
[Link]()
How to customize base in logarithmic scale:
--------------------------------------------
By using base keyword argumen.

import [Link] as plt


import numpy as np
a = [Link](10000)
b = [Link](10000)
[Link](a,b,'o-r')
#[Link]('linear')
[Link]('log',base=8)
#[Link]('linear')
[Link]('log',base=9)
[Link]()
[Link]()

You might also like