[Go to site: main page, start]

0% found this document useful (0 votes)
9 views29 pages

Matplotlib Library in Python

Matplotlib is a widely used Python library for creating 2D plots and visualizations, allowing for static, animated, and interactive graphics. It provides various plotting functions such as line plots, scatter plots, bar charts, and histograms, along with customization options for aesthetics and readability. The library also supports features like subplots, legends, markers, and gridlines to enhance data representation.

Uploaded by

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

Matplotlib Library in Python

Matplotlib is a widely used Python library for creating 2D plots and visualizations, allowing for static, animated, and interactive graphics. It provides various plotting functions such as line plots, scatter plots, bar charts, and histograms, along with customization options for aesthetics and readability. The library also supports features like subplots, legends, markers, and gridlines to enhance data representation.

Uploaded by

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

MATPLOTLIB LIBRARY IN PYTHON

What is Matplotlib?
Matplotlib is one of the most popular Python packages used for data visualization. It is a cross-platform library
for making 2D plots from data in [Link] helps in embedding plots in applications using Python GUI toolkits such
as PyQt, WxPython, or Tkinter
Matplotlib is a versatile toolkit that allows for the creation of static, animated, and interactive visualizations in the
Python programming language.

Matplotlib simplifies simple tasks and enables complex tasks to be accomplished. Following are the key aspects of
matplotlib:

 Matplotlib offers to create quality plots.


 Matplotlib offers interactive figures and customizes their visual style that can be manipulated as per need.
 Matplotlib offers export to many file formats.

Import Matplotlib
import matplotlib
Pyplot
Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported under the plt alias:
import [Link] as plt

Plotting x and y points

The plot() function is used to draw points (markers) in a diagram.

By default, the plot() function draws a line from point to point.

The function takes parameters for specifying points in the diagram.

Parameter 1 is an array containing the points on the x-axis.

Parameter 2 is an array containing the points on the y-axis.

Eample program: file [Link]


import [Link] as plt
import numpy as np
x=[Link]([3,4,5])
y=x*2
#y=[Link]([2,7,9])
[Link](x,y)
[Link]()
Types of Plots

Matplotlib supports various types of plots which are as mentioned below. Each plot type has its own function in the
library.

Name of
Definition Image
the plot

Line plot A line plot is a type of graph that displays data points connected by straight line segments.
The [Link]() function of the matplotlib library is used to create the line plot.

Scatter A scatter plot is a type of graph that represents individual data points by displaying them as
markers on a two-dimensional plane.
plot
The [Link]() function is used to plot the scatter plot.
Bar plot A bar plot or bar chart is a visual representation of categorical data using rectangular bars.
The [Link]() function is used to plot the bar plot.

A pie plot is also known as a pie chart. It is a circular statistical graphic used to illustrate
Pie plot numerical proportions. It divides a circle into sectors or slices to represent the relative sizes
or percentages of categories within a dataset.
The [Link]() function is used to plot the pie chart.

The above mentioned are the basic plots of the matplotlib library. We can also visualize the 3-d plots with the help
of Matplotlib.

Subplots

We can create multiple plots within a single figure using subplots. This is useful when we want to display multiple
plots together.

Creating a Simple Plot Using Matplotlib

The following are the key steps to create a simple plot −

Step 1: Preparing the Data

It involves in preparing the data to be plotted. This could be numeric values, lists, arrays or data loaded from files.

Step 2: Plotting Function

Using Matplotlib's pyplot API or object-oriented interface a simple plot is generated. The most common functions
include the below functions.

plot(): Creates line plots.


scatter(): Generates scatter plots.
bar(): Plots bar charts.
hist(): Creates histograms.

Step 3: Customization (Optional)

Customization involves adding labels, titles, adjusting colors, markers, axes limits, legends and other attributes to
enhance the plot's readability and aesthetics.

Step 4: Displaying the Plot

Finally displaying the plot using show() in pyplot or other appropriate methods.
Simple Line Plot: filename-simplelineplot
import [Link] as plt
import numpy as np
x=[(i-5) for i in range(20,60)]
y=[(i+5) for i in range(20,60)]
[Link](x,y)
print("customuze the plot")
[Link]("X Axis")
[Link]("Y Axis")
[Link]("Simple Line Plot")
print("\n Display the plot")
[Link]()

Simple Scatter Plot:[Link]


import [Link] as plt
import numpy as np
#x=[(i-5) for i in range(20,60)]
#y=[(i+5) for i in range(20,60)]
x=[Link]([3,5,6,9])
y=[Link]([7,12,15,18])
[Link](x,y)
print("customize the plot")
[Link]("X Axis")
[Link]("Y Axis")
[Link]("Simple scatter Plot")
print("\n Display the plot")
[Link]()
Simple Bar Plot
import [Link] as plt
import numpy as np
#x=[(i-5) for i in range(20,60)]
#y=[(i+5) for i in range(20,60)]
x=[Link]([3,5,6,9])
y=[Link]([7,12,15,18])
[Link](x,y)
print("customize the plot")
[Link]("X Axis")
[Link]("Y Axis")
[Link]("Simple Bar Plot")
print("\n Display the plot")
[Link]()
HISTOGRAM
Histogram
A histogram is a graph showing frequency distributions.
It is a graph showing the number of observations within each given interval.
Example: Say you ask for the height of 250 people, you might end up with a histogram like this:
In Matplotlib, we use the hist() function to create histograms.
The hist() function will use an array of numbers to create a histogram, the array is sent into the
function as an argument.
For simplicity we use NumPy to randomly generate an array with 250 values, where the values
will concentrate around 170, and the standard deviation is 10.

Normal distribution in Numpy


import numpy as np
x = [Link](170, 10, 250)
print(x)

Output:165.47920083 162.78525613 174.19415915 171.95902243 193.34362678


156.36010153 162.50077933 155.21962862 179.90768443 141.83712707
155.3151046 177.55192713 169.14520266 156.66606905 174.42427176
174.54939066 171.93503573 169.8632588 168.46692123 175.42444775
176.88435125 164.71167721 176.6261913 164.83359683 174.81678464
183.2744278 182.27399993 184.37464626 170.29751072 166.40736843
172.78036705 188.32109958 157.02066492 170.68684476 160.41449583
183.23046633 162.11798482 183.69685606 161.42526627 159.14211002
164.05663042 188.71477907 174.08979448 180.94104491 173.1238936
161.4993389 163.31122096 162.45962284 172.37004298 181.44759011
184.98687661 164.27222827 158.86162634 171.65940059 181.88641734
165.03203563 175.85345617 165.76637852 174.43708625 187.30165808
171.82807114 162.36877664 161.4650446 165.47046662 182.68044303
155.56591842 147.20033597 161.94067249 164.66897094 168.15545769
181.93152155 163.06809401 166.41708137 185.13837148 184.30940995
169.46117267 167.53646466 165.21479853 165.42493908 174.82265534
163.39112462 169.92028482 167.88387139 166.36609639 172.73490217
161.10403313 145.00917747 158.91933011 185.33423941 176.9846337
170.74463505 170.55714261 170.46357459 161.09648337 189.76144981
187.5992355 165.53368756 178.98493144 171.66572447 168.66501877
146.70764107 169.50014369 175.83396457 158.96613634 159.80363209
171.52213008 172.75065219 172.56007671 171]

Program code: Histogram


import [Link] as plt
import numpy as np
x=[Link](170,10,250)
[Link](x)
[Link]("Normal distribution")
[Link]("X Axis")
[Link]("Y Axis")
[Link]()
MARKER

In Matplotlib markers are used to highlight individual data points on a plot. The marker parameter in
the plot() function is used to specify the marker style. The following is the syntax for using markers in Matplotlib.

Syntax

[Link](x,y,marker=’marker_style’)

x and y − Arrays or sequences of values representing the data points to be plotted.

marker − Specifies the marker style to be used. It can be a string or one of the following marker styles:
[Link]. Marker & Definition

1 .
Point marker

2 ,
Pixel marker

3 o
Circle marker

4 v
Triangle down marker

5 ^
Triangle up marker

6 Triangle left marker

7 >
Triangle right marker

8 1
Downward-pointing triangle marker

9 2
Upward-pointing triangle marker

10 3
Left-pointing triangle marker

11 4
Right-pointing triangle marker
12 s
Square marker

13 p
Pentagon marker

14 *
Star marker

15 h
Hexagon marker (1)

16 H
Hexagon marker (2)

17 +
Plus marker

18 x
Cross marker

19 D
Diamond marker

20 d
Thin diamond marker

21 −
Horizontal line marker

Scatterplot with pentagonal marker

Here in this example we are creating the scatterplot with the pentagonal marker by using the scatter() function of
the pyplot module.

Example1:Scatter plot with marker =’pentagon’


import [Link] as plt
import numpy as np
#x=[(i-5) for i in range(20,60)]
#y=[(i+5) for i in range(20,60)]
x=[Link]([3,5,6,9])
y=[Link]([7,12,15,18])
[Link](x,y,marker='p')
print("customize the plot")
[Link]("X Axis")
[Link]("Y Axis")
[Link]("Simple Line Plot")
print("\n Display the plot")
[Link]()

Example2 :Line plot with marker =’square’


import [Link] as plt
import numpy as np
#x=[(i-5) for i in range(20,60)]
#y=[(i+5) for i in range(20,60)]
x=[Link]([3,5,6,9])
y=[Link]([7,12,15,18])
[Link](x,y,marker='s')
print("customize the plot")
[Link]("X Axis")
[Link]("Y Axis")
[Link]("Simple Line Plot")
print("\n Display the plot")
[Link]()

LEGEND()
legend in a graph provides a visual representation of the data depicted along the Y-axis, often referred to as the graph series. It is
a box containing a symbol and a label for each series in the graph. A series could be a line in a line chart, a bar in a bar chart, and
so on. The legend is helpful when you have multiple data series on the same plot, and you want to distinguish between them. In
the following image, we can observe the legend in a plot (highlighted with a red color rectangle) −

The function can be called in different ways, depending on how you want to customize the legend.

Matplotlib automatically determines the elements to be added to the legend while call legend() without passing any extra
arguments,. The labels for these elements are taken from the artists in the plot. You can specify these labels either at the time of
creating the artist or by using the set_label() method.

Manually adding the legend

You can pass an iterable of legend artists followed by an iterable of legend labels to explicitly control which artists have a legend
entry.

Program code: filename-


import [Link] as plt
x=[3,1,8,9]
y=[4,5,10,12]
y1=[8,3,1,7]
line,=[Link](x,y,marker='*',label='stright line')
##line1,=[Link](x,y1,marker='s')
##line1.set_label('line based marks')
[Link]()
##line,=[Link](x,y,marker='p')
##line1,=[Link](x,y1,marker='o')
##[Link]([line,line1],['Label1','Label2'])
[Link]('graph')
[Link]('Values')
[Link]('frequency')
[Link]()
Line and color reference
The line and color reference in Matplotlib allows you to customise the appearance of plot lines and markers. You
can quickly set the line style and color to enhance visual clarity and aesthetics.

Line Style Reference

Line Style Symbol

Solid line '-'

Dashed line ' ┈'

Dash-dot line '-.'

Dotted line ':'

Long dashed line '--'

Custom 'dotte
dash d'

While using bar chart we can’t use marker becoz it shows only in rectangular shape.

Program code:

import [Link] as plt


import numpy as np
x=['car','Benze','I20']
y=[12,16,18]
[Link](x,y,linestyle='-.',label='car weightage')
[Link]()
[Link]("car garbage")
[Link]("car names")
[Link]("weightage of parts")
[Link]()
Background Colors in Matplotlib

Matplotlib provides extensive options to control background colors enabling users to customize the visual
appearance of plots and figures. The background color plays a crucial role in enhancing the aesthetics and
readability of visualizations, setting the tone and mood for the displayed data.

The figure's background color encompasses the entire area where plots are rendered. By default it's often white but it
can be changed using [Link](facecolor='color_name') or [Link]().set_facecolor('color_name'). This affects
the area around the plots.

The plot background color on the other hand refers to the area within the plot's axes. It can be altered
with [Link]().set_facecolor('color_name') by providing a different background color within the actual plot.

Program code:

import [Link] as plt


import numpy as np
y=[Link](0,10,100)
y1=[Link](y)
[Link](facecolor='orange') ## outside backgroud color
[Link](y,y1,marker='s',color='blue')
ax=[Link]().set_facecolor('yellow')##inside color
[Link]("car garbage",color='#00FF0')
[Link]("car names",color='pink')
[Link]("weightage of parts",color='g')
[Link]()

Grid

Grids in Matplotlib are intersecting lines that provide a structured reference for data points, improving readability
and interpretation of plots. grid() function in the Pyplot module is used to configure grid lines in a plot.
The [Link]() method adds major gridlines to the plot with additional customization options including adjusting
the linestyle, linewidth, color, and transparency.

Basic Plot with Grids

In Matplotlib, the default grid is a set of major gridlines that align with the major tick marks on both the x-axis and
the y-axis.
Program code:

import [Link] as plt


import numpy as np
x = [Link](0, 20, 100)
y = [Link](x)
# create a plot
fig, ax = [Link](figsize=(10,7))
# Plot the data
[Link](x, y)
# Add grid
#[Link](True)
# Show the plot
[Link]()

Syntax
[Link](b=True, color='grey', linewidth=1.4, axis='', linestyle='-.')

Customizing Grid

Customizing gridlines includes linestyle, linewidth, color, and transparency.


Program code:
import [Link] as plt
import numpy as np
x = [Link](0, 20, 100)
y = [Link](x)
# create a plot
fig, ax = [Link](figsize=(10,7))
# Plot the data
[Link](x, y)
#customize grid
#[Link](True,color='green',linewidth=1.5,linestyle='-')
# set the title
[Link]('Basic Plot with Grids',color='y')
# Show the plot
[Link]()

Displaying Grid Lines for Specific Axes


Matplotlib allows us to display gridlines only for the x-axis or y-axis.
import [Link] as plt
import numpy as np
x = [Link](0, 20, 100)
y = [Link](x)
# create a plot
fig, ax = [Link](figsize=(10,7))
# Plot the data
[Link](x, y)
#customize grid
#[Link](True,color='y',linewidth=1,linestyle=':',axis='x')
[Link](True,color='y',linewidth=1,linestyle='--',axis='y')
# set the title
[Link]('Basic Plot with Grids',color='y')
# Show the plot
[Link]()
SUBPLOT
Matplotlib is a widely used data visualization library in Python that provides powerful tools for creating a variety
of plots. One of the most useful features of Matplotlib is its ability to create multiple subplots within a single
figure using the [Link]() method. This allows users to display multiple related visualizations side by side,
making data analysis more insightful and effective.
Subplots in Matplotlib refer to multiple plots arranged within a single figure. The [Link]()
method provides an easy way to create a figure with multiple plots. Given the number of rows and columns, it
returns a tuple (fig, ax), where fig is the entire figure object and ax is an array of axes objects representing
individual subplots

Program code:
import [Link] as plt
import numpy as np
x = [Link](0, 20, 100)
y = [Link](x)
y1= [Link](x)
# create a plot
fig,(ax1,ax2) = [Link](nrows=1,ncols=2,figsize=(10,7))
# Plot the data'
[Link](x,y,'r-.',label='cos')
[Link](x,y,color='g',linestyle='--',label='tan')
#legend()
[Link]()
[Link]()
# set the title
ax1.set_title('cos value',color='y')
ax2.set_title('sine value',color='b')
# Show the plot
[Link]()

Accessing Subplots using Axes Array

In this example subplots are access through index of the axes array. And legend is add to the each subplot.

Program code:

import [Link] as plt


import numpy as np
x = [Link](0, 20, 100)
y = [Link](x)
y1= [Link](x)
# create a plot
fig,ax = [Link](2,2,figsize=(10,7))
# Plot the data by axes
ax[0,0].plot(x,y,'r-.',label='cos')
ax[0,1].plot(x,y,color='lightgreen',linestyle='--',label='tan')
ax[1,0].plot(x,y,color='grey',linestyle='-',label='sine')
ax[1,1].plot(x,y,'y:',label='cosine')
# access legend()by loop
for axes in [Link]:
[Link]()
# set the title
ax[0,0].set_title('cos value',color='y')
ax[0,1].set_title('tan value',color='darkblue')
ax[1,0].set_title('sine value',color='orange')
ax[1,1].set_title('cosec value',color='violet')
#Adjust layout
plt.tight_layout()
# Show the plot
[Link]()

BARPLOT ACCESS BY AXES

import [Link] as plt


import pandas as pd
##create dataframe
data={'car':['Benze','I20','Duster','Toyato'],'v1':[13,77,23,55],'v2':[34,12,2,5]}
df=[Link](data)
print(df)
# create a plot
fig,ax = [Link](nrows=1,ncols=3,figsize=(8,7))
# Plot the data by axes
[Link](kind='bar',x='car',y='v1',color='red',linestyle='-.',label='cos',ax=ax[0])
[Link](kind='bar',x='car',y='v2',color='lightgreen',linestyle='--',label='tan',ax=ax[1])
[Link](kind='bar',x='car',y='v1',color='grey',linestyle='-',label='sine',ax=ax[2])
# access legend()by loop
for axes in [Link]:
[Link]()
# set the title
ax[0].set_title('cos value',color='y')
ax[1].set_title('tan value',color='darkblue')
ax[2].set_title('sine value',color='orange’)
#Adjust layout
plt.tight_layout()
# Show the plot
[Link]()
FONT

Fonts play a crucial role in customizing text elements within plots. We can control font styles, sizes, families and
other properties to enhance the appearance and readability of text in our visualizations.

In Matplotlib library Fonts refer to the typefaces used for rendering text in plots and visualizations. Fonts play a
significant role in customizing the appearance of text elements such as labels, titles, annotations and legends within
plots.

Key Aspects of Fonts in Matplotlib library

Font Family − Refers to the style or category of the font. Common font families include serif, sans-serif,
monospace etc. Each family has its own visual characteristics.

Font Style − Determines the appearance of text such as normal, italic or oblique.

Font Weight − Specifies the thickness or boldness of the font ranging from normal to various levels of boldness.

Program code:

import [Link] as plt


import numpy as np
x=['car','bike','cycle','auto']
y=[4,2,2,4]
fig,ax=[Link](figsize=(8,6))
#plot data
[Link](x,y,marker='*',linestyle='--',color='darkgreen',label='L1')
##legend
[Link]()
##grid
[Link]()
##customize
[Link]('vehiclenames and wheelcount',color='blue',fontname='arial',fontsize=12,fontstyle='italic',fontweight='bold')
[Link]('vehicle names',color='darkgreen',fontname='Times new
roman',fontsize=10,fontstyle='oblique',fontweight='bold')
[Link]('count of wheels',color='navy',fontname='sans-serif',fontsize=9,fontstyle='italic',fontweight='bold')
# Show the plot
[Link]()
SPINES:

In Matplotlib library spines refer to the borders or edges of a plot that frame the data area. These spines encompass
the boundaries of the plot defining the area where data points are displayed. By default a plot has four spines such as
top, bottom, left and right.

Manipulating spines in Matplotlib offers flexibility in designing the visual aspects of a plot by allowing for a more
tailored and aesthetically pleasing presentation of data.

Key Characteristics of Spines

The following are the characteristics of spines.

Borders of the Plot − Spines form the borders of the plot area enclose the region where data is visualized.

Configurable Properties − Each spine top, bottom, left, and right can be customized individually by allowing
adjustments to their appearance, color, thickness and visibility.
Visibility Control − Spines can be made visible or hidden to modify the appearance of the plot.

Types of spines

Now lets see the each and every spine available in a plot in detail.

Top Spine

The Top spine refers to the horizontal line at the top of the plot area that corresponds to the upper boundary of the y-
axis. It's one of the four spines such as top, bottom, left and right that form the borders around the plot.

Characteristics of the Top Spine

Boundary Line − The top spine represents the upper boundary of the plot area along the y-axis.

Default Visibility − By default the top spine is visible in Matplotlib plots.

Customization − Similar to other spines the top spine can be customized in terms of its visibility, color, linestyle
and linewidth.

Removing Top Spine

In this example [Link]['top'].set_visible(False) hides the top spine by removing the upper boundary of the plot
area along the y-axis.

Customization − Similar to other spines the bottom spine can be customized in terms of its visibility, color, line
style, thickness and position.
[Link]['top'].set_visible(True)
[Link]['top'].set_color(‘green’)
[Link]['top'].set_linewidth(1.8)

Program code:

import [Link] as plt


import numpy as np
x=['car','bike','cycle','auto']
y=[4,2,2,4]
fig,ax=[Link](figsize=(8,6))
#plot data
[Link](x,y,marker='*',linestyle='--',color='darkgreen',label='L1')
##legend
[Link]()
##grid
[Link]()
[Link]('vehiclenames and wheelcount',color='blue',fontname='arial',fontsize=12,fontstyle='italic',fontweight='bold')
[Link]('vehicle names',color='darkgreen',fontname='Times new
roman',fontsize=10,fontstyle='oblique',fontweight='bold')
[Link]('count of wheels',color='navy',fontname='sans-serif',fontsize=9,fontstyle='italic',fontweight='bold')
##remove top frame
[Link]['top'].set_visible(False)
##customize spines
[Link]['left'].set_color('yellow')
[Link]['left'].set_linewidth(1.5)
[Link]['left'].set_visible(True)
# Show the plot
[Link]()

You might also like