Data visualisation is the graphical or pictorial representation of data using graphs, charts, and other visual elements. It helps in making inferences, drawing conclusions, and making important business decisions by presenting complex numerical analysis in an easily understandable format.
Technical Profile: Matplotlib Library
The pyplot module of Matplotlib contains a collection of functions to create and modify plots. A figure is the overall window where the outputs are plotted, containing plotting areas, legends, axis labels, ticks, and titles.
Install Matplotlib via pip:
pip install matplotlib
Import the pyplot module with an alias:
import matplotlib.pyplot as plt
To plot $x$ versus $y$, use plt.plot(x, y) . To display the plot, use plt.show() .
import matplotlib.pyplot as plt
date = ["25/12", "26/12", "27/12"]
temp = [8.5, 10.5, 6.8]
plt.plot(date, temp)
plt.show()
Table 4.1: List of Pyplot functions to plot different charts
| Computing Method | Exact Syntactic Execution Signature | Supported Parameters | Algorithmic Purpose |
|---|---|---|---|
| plot() |
plot(*args, scalex, scaley, data)
|
x, y, markers, line properties | Plot x versus y as lines and/or markers. |
| bar() |
bar(x, height, width, bottom, align, data)
|
x, height, width, align, color | Make a bar plot. |
| boxplot() |
boxplot(x, notch, sym, vert, whis, ...)
|
x, vert, notch, sym | Make a box and whisker plot. |
| hist() |
hist(x, bins, range, density, weights, ...)
|
x, bins, range, color, hatch | Plot a histogram. |
| pie() |
pie(x, explode, labels, colors, autopct, ...)
|
x, explode, labels, colors, autopct | Plot a pie chart. |
| scatter() |
scatter(x, y, s, c, marker, cmap, norm, ...)
|
x, y, s (size), c (color), marker | A scatter plot of x versus y. |
Pyplot provides numerous functions to customise charts by adding titles, labels, grids, and legends.
Table 4.2: List of Pyplot functions to customise plots
| Function | Exact Syntactic Execution Signature | Supported Parameters | Algorithmic Purpose |
|---|---|---|---|
| grid() |
grid([b, which, axis])
|
b (boolean), axis ('x', 'y', 'both') | Configure the grid lines. |
| legend() |
legend(*args, **kwargs)
|
loc, labels, shadow | Place a legend on the axes. |
| savefig() |
savefig(*args, **kwargs)
|
fname, dpi, format | Save the current figure to a file. |
| show() |
show(*args, **kw)
|
None | Display all figures. |
| title() |
title(label, fontdict, loc, pad)
|
label (str), loc, fontsize | Set a title for the axes. |
| xlabel() |
xlabel(xlabel, fontdict, labelpad)
|
xlabel (str), labelpad | Set the label for the x-axis. |
| xticks() |
xticks([ticks, labels])
|
ticks (list), labels (list) | Get or set the current tick locations and labels of the x-axis. |
| ylabel() |
ylabel(ylabel, fontdict, labelpad)
|
ylabel (str), labelpad | Set the label for the y-axis. |
| yticks() |
yticks([ticks, labels])
|
ticks (list), labels (list) | Get or set the current tick locations and labels of the y-axis. |
Plots can be styled using markers, custom colors, linewidths, and linestyles.
Table 4.3: Some of the Matplotlib Markers
| Marker Code | Description | Marker Code | Description |
|---|---|---|---|
"."
|
Point |
"8"
|
Octagon |
","
|
Pixel |
"s"
|
Square |
"o"
|
Circle |
"p"
|
Pentagon |
"v"
|
Triangle Down |
"P"
|
Plus (filled) |
"^"
|
Triangle Up |
"*"
|
Star |
"<"
|
Triangle Left |
"h"
|
Hexagon 1 |
">"
|
Triangle Right |
"H"
|
Hexagon 2 |
"1"
|
Tri Down |
"+"
|
Plus |
"2"
|
Tri Up |
"x"
|
X |
"3"
|
Tri Left |
"X"
|
X (filled) |
"4"
|
Tri Right |
"D"
|
Diamond |
Table 4.4: Colour Abbreviations
| Character Code | Colour Name |
|---|---|
'b'
|
Blue |
'g'
|
Green |
'r'
|
Red |
'c'
|
Cyan |
'm'
|
Magenta |
'y'
|
Yellow |
'k'
|
Black |
'w'
|
White |
Linewidth and Linestyle:
Linewidth is specified in pixels (default is 1). Linestyle can take values like
"solid"
,
"dotted"
,
"dashed"
, or
"dashdot"
.
Pandas Series and DataFrame objects have a built-in .plot() method, which acts as a wrapper around Matplotlib's pyplot.plot() .
Table 4.5: Arguments accepted by kind for different plots
| kind Value | Plot Type |
|---|---|
'line'
|
Line plot (default) |
'bar'
|
Vertical bar plot |
'barh'
|
Horizontal bar plot |
'hist'
|
Histogram |
'box'
|
Boxplot |
'area'
|
Area plot |
'pie'
|
Pie plot |
'scatter'
|
Scatter plot |
Line charts are used to show continuous datasets and visualise growth or decline over time.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("MelaSales.csv")
df.plot(kind='line', color=['red', 'blue', 'brown'])
plt.title('Mela Sales Report')
plt.xlabel('Days')
plt.ylabel('Sales in Rs')
plt.show()
Bar charts are preferred for comparing discrete categories. Unlike line plots, bar charts can plot strings directly on the x-axis.
df.plot(kind='bar', x='Day', title='Mela Sales Report')
plt.ylabel('Sales in Rs')
plt.show()
Customising bar charts with colors, edgecolors, linewidths, and linestyles:
df.plot(kind='bar', x='Day', title='Mela Sales Report', color=['red', 'yellow', 'purple'], edgecolor='Green', linewidth=2, linestyle='--')
Histograms represent the frequency distribution of continuous numerical data by grouping values into intervals called bins .
df.plot(kind='hist')
plt.show()
Customising histograms with custom bins, edgecolors, hatch patterns, and fill properties:
df.plot(kind='hist', edgecolor='Green', linewidth=2, linestyle=':', fill=False, hatch='o')
Scatter charts use dots to represent values for two different variables to show their relationship or correlation.
plt.scatter(x=discount, y=saleInRs, s=size, color='red', linewidth=3, marker='*', edgecolor='blue')
A box plot visually represents the statistical summary of a dataset: Minimum, Quartile 1 (Q1), Median (Q2), Quartile 3 (Q3), and Maximum. It also highlights outliers (data points numerically distant from the rest of the data).
df.plot(kind='box')
plt.title('Performance Analysis')
plt.xlabel('Subjects')
plt.ylabel('Marks')
plt.show()
To plot a horizontal box plot, set vert=False :
df.plot(kind='box', title='Compare Resorts', color='red', vert=False)
A pie chart represents numerical data proportionally as sectors of a circle. To plot a pie chart, either the column label
y
or
subplots=True
must be specified.
df.plot(kind='pie', y='ForestCover', title='Forest cover of North Eastern states', legend=False, explode=exp, autopct="%.2f", colors=c)