MatplotLib - Charts
MatplotLib - Charts
Matplotlib
Matplotlib is a low-level library of Python
which is used for data visualization. It is easy to
use and emulates MATLAB like graphs and
visualization. This library is built on the top of
NumPy arrays and consist of several plots like
line chart, bar chart, histogram, etc. It provides
a lot of flexibility but at the cost of writing more
code.
Installation
We will use the pip command to install this
module. If you do not have pip installed then
refer to the article, Download and install pip
Latest Version.
WaveBasis 14-day Free
Trial
WaveBasis
Example:
Python3
plt.show()
Output:
Adding Title
The title() method in matplotlib module is used
to specify the title of the visualization depicted
and displays the title using various attributes.
Syntax:
matplotlib.pyplot.title(label,
fontdict=None, loc=’center’, pad=None,
**kwargs)
Example:
Python3
plt.show()
Output:
Example:
Python3
plt.show()
Output:
Syntax:
matplotlib.pyplot.xlabel(xlabel,
fontdict=None, labelpad=None,
**kwargs)
matplotlib.pyplot.ylabel(ylabel,
fontdict=None, labelpad=None,
**kwargs)
Example:
Python3
plt.show()
Output:
Python3
plt.show()
Output:
Adding Legends
A legend is an area describing the elements of
the graph. In simple terms, it reflects the data
displayed in the graph’s Y-axis. It generally
appears as the box containing a small sample
of each color on the graph and a small
description of what this data means.
The attribute bbox_to_anchor=(x, y) of legend()
function is used to specify the coordinates of
the legend, and the attribute ncol represents
the number of columns that the legend has. Its
default value is 1.
Syntax:
matplotlib.pyplot.legend([“name1”,
“name2”], bbox_to_anchor=(x, y), ncol=1)
Example:
Python3
# Adding legends
plt.legend(["GFG"])
plt.show()
Output:
Before moving any further with Matplotlib let’s
discuss some important classes that will be
used further in the tutorial. These classes are –
Figure
Axes
Figure class
Consider the figure class as the overall window
or page on which everything is drawn. It is a
top-level container that contains one or more
axes. A figure can be created using the figure()
method.
Syntax:
class
matplotlib.figure.Figure(figsize=None,
dpi=None, facecolor=None,
edgecolor=None, linewidth=0.0,
frameon=None, subplotpars=None,
tight_layout=None,
constrained_layout=None)
Example:
Python3
# Python program to show pyplot module
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
# Adding legends
plt.legend(["GFG"])
plt.show()
Output:
Syntax:
Example:
Python3
# Python program to show pyplot module
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
# Setting Title
ax.set_title("Linear Graph")
# Setting Label
ax.set_xlabel("X-Axis")
ax.set_ylabel("Y-Axis")
# Adding Legend
ax.legend(labels = ('line 1', 'line 2'))
plt.show()
Output:
Multiple Plots
We have learned about the basic components
of a graph that can be added so that it can
convey more information. One method can be
by calling the plot function again and again
with a different set of values as shown in the
above example. Now let’s see how to plot
multiple graphs using some functions and also
how to plot subplots.
Syntax:
Example:
Python3
plt.show()
Output:
Method 2: Using subplot() method.
Syntax:
subplot(pos, **kwargs)
subplot(ax)
Example:
Python3
Output:
Syntax:
matplotlib.pyplot.subplots(nrows=1,
ncols=1, sharex=False, sharey=False,
squeeze=True, subplot_kw=None,
gridspec_kw=None, **fig_kw)
Example:
Python3
Skip to content
Pandas Numpy Seaborn Ploty Data visualization Data Analysis Power BI Tableau Machine Learning Deep Learning
Output:
Data Visualization
with Matplolib and
Seaborn
Data Visualization
with Matplotlib
Matplotlib
Introduction
Matplotlib Multiple Method 4: Using subplot2grid() method
Plots
This function creates axes object at a specified
Matplotlib 3D Plots
Python3
axes2 = plt.subplot2grid (
(7, 1), (2, 0), rowspan = 2, colspan = 1)
Output:
Line Chart
Syntax:
matplotlib.pyplot.plot(\*args,
scalex=True, scaley=True, data=None,
\*\*kwargs)
Example:
Python3
plt.show()
Output:
Character Definition
– Solid line
— Dashed line
-. dash-dot line
: Dotted line
. Point marker
o Circle marker
, Pixel marker
v triangle_down marker
v triangle_down marker
^ triangle_up marker
1 tri_down marker
2 tri_up marker
3 tri_left marker
4 tri_right marker
s square marker
p pentagon marker
* star marker
h hexagon1 marker
H hexagon2 marker
+ Plus marker
x X marker
D Diamond marker
d thin_diamond marker
| vline marker
_ hline marker
Example:
Python3
plt.show()
Output:
Bar Chart
Example:
Python3
plt.show()
Output:
Example:
Python3
plt.show()
Output:
Histogram
A histogram is basically used to represent data
provided in a form of some groups. It is a type
of bar plot where the X-axis represents the bin
ranges while the Y-axis gives information about
frequency. The hist() function is used to
compute and create histogram of x.
Syntax:
matplotlib.pyplot.hist(x, bins=None,
range=None, density=False,
weights=None, cumulative=False,
bottom=None, histtype=’bar’, align=’mid’,
orientation=’vertical’, rwidth=None,
log=False, color=None, label=None,
stacked=False, \*, data=None, \*\*kwargs)
Example:
Python3
plt.show()
Output:
Customization that is available for the
Histogram –
Example:
Python3
plt.show()
Output:
Scatter Plot
Syntax:
matplotlib.pyplot.scatter(x_axis_data,
y_axis_data, s=None, c=None,
marker=None, cmap=None, vmin=None,
vmax=None, alpha=None,
linewidths=None, edgecolors=None
Example:
Python3
import matplotlib.pyplot as plt
import pandas as pd
plt.show()
Output:
Python3
import matplotlib.pyplot as plt
import pandas as pd
plt.show()
Output:
Pie Chart
Syntax:
matplotlib.pyplot.pie(data,
explode=None, labels=None,
colors=None, autopct=None,
shadow=False)
Example:
Python3
plt.show()
Output:
Example:
Python3
plt.show()
Output:
Saving a Plot
For saving a plot in a file on storage disk,
savefig() method is used. A file can be saved in
many formats like .png, .jpg, .pdf, etc.
Syntax:
pyplot.savefig(fname, dpi=None,
facecolor=’w’, edgecolor=’w’,
orientation=’portrait’, papertype=None,
format=None, transparent=False,
bbox_inches=None, pad_inches=0.1,
frameon=None, metadata=None)
Example:
Python3
# Creating data
year = ['2010', '2002', '2004', '2006', '2008']
production = [25, 15, 35, 30, 10]
# Plotting barchart
plt.bar(year, production)
Output: