Data Visualization (using matplotlib)

Mohit Sharma
Incedge & Co.
Published in
8 min readOct 23, 2018

(Note:- this blog is dedicated to the novice in the field of Data Visualization)

Data visualization

Is viewed by many disciplines as a modern equivalent of visual communication. It involves the creation and study of the visual representation of data.

To communicate information clearly and efficiently, data visualization uses statistical graphics, plots, information graphics, and other tools. Numerical data may be encoded using dots, lines, or bars, to visually communicate a quantitative message. Effective visualization helps users analyze and reason about data and evidence. It makes complex data more accessible, understandable and usable. Users may have particular analytical tasks, such as making comparisons or understanding causality, and the design principle of the graphic (i.e., showing comparisons or showing causality) follows the task. Tables are generally used where users will look up a specific measurement, while charts of various types are used to show patterns or relationships in the data for one or more variables.

Data visualization is both an art and a science. It is viewed as a branch of descriptive statistics by some, but also as a grounded theory development tool by others. Increased amounts of data created by Internet activity and an expanding number of sensors in the environment are referred to as “big data” or the Internet of things. Processing, analyzing and communicating this data present ethical and analytical challenges for data visualization. The field of data science and practitioners called data scientists to help address this challenge.

Coming Weeks I’ll explain with code each and every one of below, but today we're sticking to Matplotlib only.

  1. Matplotlib
  2. Pandas Built-in Data Visualization
  3. Seaborn
  4. Plotly and Cufflinks
  5. Geographical plotting

Matplotlib

Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. Matplotlib can be used in Python scripts, the Python and IPython shells, the Jupyter notebook, web application servers, and four graphical user interface toolkits.

  • Matplotlib is the most popular plotting library for python.
  • It gives you control over every aspect of a figure.
  • It was designed to have a similar feel to Matlab's graphical plotting.

Import the libraries

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
# matplotlib.pyplot is a state-based interface to matplotlib. It provides a MATLAB-like way of plotting.
# pyplot is mainly intended for interactive plots and simple cases of programmatic plot generation:
# %matplotlib inline means all the plots will now show in notebook itself.
  • Note — If you’re using Matplotlib from within a python script, then you have to add plt.show() method inside the file to be able display your plot.

Two ways to plot

  • Functional Method
  • Object-Oriented Method

Functional Method

Using the basic matplotlib command, we can easily create a plot. Remember, if no plot was displayed or if you’re using Matplotlib from within a python script, don’t forget to add plt.show() at the last line to display your plot.

General Text x = np.linspace(start, stop, num(by default =50), others) y = Any equation for example np.sqrt(x) or x ** 2 etc.

Steps In-

  1. plt.plot(x,y,color, others) Plot y versus x as lines and/or markers.

2. plt.xlable(“Your Text”) Set the x-axis label of the current axes.

3. plt.ylable(“Your Text”) Set the y-axis label of the current axes.

4. plt.set_title(“Your Title”) Set a title of the current axes.

5. plt.show() Display a figure.

Object-Oriented Method

Another way to create a plot. The idea here is to create figure objects and call methods of it. To create figure we use .figure() method. Once, you created a figure you need to add a set of axes to it using .add_axes() method.

Steps In-

  1. fig = plt.figure() Creates a new figure.

2. axes = fig.add_axes([left,bottom,width,height], projection =’Your choice’)
Add an axes at position [left, bottom, width, height] where all quantities are in fractions of figure width and height

3. axes.plot(x,y) Plot y versus x as lines and/or markers.

4. axes.set_xlabel(“Your Text”) Set the label for the x-axis.

5. axes.set_ylabel(“Your Text”) Set the label for the x-axis.

6. axes.set_title(“Your Title”) Set the title of the current axes.

Functional Method

x = np.linspace(0,10,100)
y = x**2
y = np.sqrt(x)
plt.plot(x,y,'r')plt.xlabel("X Label")
plt.ylabel("Y Label")
plt.title("X vs Y")
plt.show()
Figure 1

In [3]:

# Now if you want to plot mutliple plot together you can use subplot()plt.subplot(1,2,1)
plt.plot(x,y,'b')
# subplot(no of rows, no of columns, plot no you are refering to)plt.subplot(1,2,2)
plt.plot(x,y,'g')
plt.show()
Figure 2

Object-Oriented Method

In [4]:

fig = plt.figure()
axes = fig.add_axes([0.1,0.1,0.8,0.8])
axes.plot(x,y)axes.set_xlabel("X Label")
axes.set_ylabel("Y Label")
axes.set_title("X vs Y")

Out[4]:

Text(0.5,1,'X vs Y')
Figure 3

In [5]:

fig = plt.figure()axes1 = fig.add_axes([0.1,0.1,0.8,0.8])
axes2 = fig.add_axes([0.4,0.55,0.4,0.3])
axes1.plot([0.1,0.50,0.13,0.16],[10,15,18,25],'red')
axes2.plot(y,x,'green')

Out[5]:

[<matplotlib.lines.Line2D at 0x8f7c6a0>]
Figure 4

How to create subplot using Object Oriented Method

In [6]:

fig, axes = plt.subplots(nrows=1,ncols=2)

# By Default plt.subplots(nrows=1,ncols=1,sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None)
axes[0].plot(x,y,'red')
axes[0].set_title("Y versus X")
axes[1].plot(y,x,'green')
axes[1].set_title("X versus Y")
plt.tight_layout()
# Always put in the end for not overlap
Figure 5

Figure Size and DPI

In [7]:

fig = plt.figure(figsize=(3,2),dpi= 100)# Creates a new figure.
# figsize : tuple of integers, optional, default: None
# width, height in inches. If not provided, defaults to rc
# figure.figsize.
# dpi(dots per inch) : integer, optional, default: None
# resolution of the figure. If not provided, defaults to rc figure.dpi.
ax = fig.add_axes([0,0,1,1])
ax.plot(x,y)

Out[7]:

[<matplotlib.lines.Line2D at 0x9063eb8>]
Figure 6

In [8]:

fig, axes = plt.subplots(nrows=2,ncols=1,figsize=(8,2),dpi=100)axes[0].plot(x,y,'b')
axes[1].plot(y,x,'p')
plt.tight_layout()
Figure 7

Save a Figure

In [9]:

fig.savefig("My_Figure.png")

In [10]:

# If you are interested in particular directory you can give the whole path of that directory
# You can save the figure with .jpg or .jpeg etc.
fig.savefig("C://Users//pc//Downloads//Anaconda Practice//My_Figure.png")

Legends

In [11]:

fig = plt.figure()ax = fig.add_axes([0,0,1,1])ax.plot(x,x**2,label = 'X Squared')
ax.plot(x,x**3,label='X Cubed')
ax.legend(loc =0)

Out[11]:

<matplotlib.legend.Legend at 0x90aa198>
Figure 8

In [12]:

fig = plt.figure()ax = fig.add_axes([0,0,1,1])ax.plot(x,x**2,label = 'X Squared')
ax.plot(x,x**3,label='X Cubed')
ax.legend(loc=5)

Out[12]:

<matplotlib.legend.Legend at 0xa0e8048>
Figure 9

Now, your turn to play with legend and make sure to put the value between 0–10 only.

Plot Appearance

In [13]:

fig = plt.figure()ax = fig.add_axes([0,0,1,1])
ax.plot(x,y)
# ax.plot(x,y,color='orange')# You can also use #RGB Hex Code if you knowax.plot(x,y,color='#FF8c00')

Out[13]:

[<matplotlib.lines.Line2D at 0xa14b390>]
Figure 10

Line Width and Style

In [14]:

fig = plt.figure()ax = fig.add_axes([0,0,1,1])
ax.plot(x,y)
ax.plot(x,y,color='#FF8c00',linewidth =20)

Out[14]:

[<matplotlib.lines.Line2D at 0xa1ac1d0>]
Figure 11

In [15]:

fig = plt.figure()ax = fig.add_axes([0,0,1,1])
ax.plot(x,y)
ax.plot(x,y,color='#FF8c00',lw =2)# Note: You can also use shortcut by writing lw rather than linewidth

Out[15]:

[<matplotlib.lines.Line2D at 0xa203f98>]
Figure 12

In [16]:

fig = plt.figure()ax = fig.add_axes([0,0,1,1])
ax.plot(x,y)
ax.plot(x,y,color='#FF8c00',linewidth =5,alpha=0.4)# alpha: float (0.0 transparent through 1.0 opaque)

Out[16]:

[<matplotlib.lines.Line2D at 0xa263c50>]
Figure 13

In [17]:

fig = plt.figure()ax = fig.add_axes([0,0,1,1])
ax.plot(x,y)
ax.plot(x,y,color='#FF8c00',linewidth =5.5,alpha=0.8904,linestyle=':')# linestyle or ls: ['solid' | 'dashed', 'dashdot', 'dotted' | (offset, on-off-dash-seq)
# | ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` | ``' '`` | ``''``]
# linewidth or lw: float value in points # alpha: float (0.0 transparent through 1.0 opaque)

Out[17]:

[<matplotlib.lines.Line2D at 0xa2c2978>]
Figure 14

Markers

In [18]:

fig = plt.figure()ax = fig.add_axes([0,0,1,1])
ax.plot(x,y)
ax.plot(x,y,color='#FF8c00',linewidth =3,alpha=0.8904,linestyle='-', marker = 'o')# linestyle or ls: ['solid' | 'dashed', 'dashdot', 'dotted' | (offset, on-off-dash-seq)
# | ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` | ``' '`` | ``''``]
# linewidth or lw: float value in points # alpha: float (0.0 transparent through 1.0 opaque) # marker: :mod:`A valid marker style <matplotlib.markers>`

Out[18]:

[<matplotlib.lines.Line2D at 0xa3246a0>]
Figure 15

In [19]:

# To add markersize 
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.plot(x,y)
ax.plot(x,y,color='#FF8c00',linewidth =3,alpha=0.8904,linestyle='-', marker = 'o', markersize=18)# linestyle or ls: ['solid' | 'dashed', 'dashdot', 'dotted' | (offset, on-off-dash-seq)
# | ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` | ``' '`` | ``''``]
# linewidth or lw: float value in points # alpha: float (0.0 transparent through 1.0 opaque) # marker: :mod:`A valid marker style <matplotlib.markers>`

Out[19]:

[<matplotlib.lines.Line2D at 0xa3873c8>]
Figure 16

In [20]:

fig = plt.figure()ax = fig.add_axes([0,0,1,1])
ax.plot(x,y)
ax.plot(x,y,color='#FF8c00',linewidth =3,alpha=0.8904,linestyle='-', marker = 'o', markersize=20,markerfacecolor='blue',
markeredgewidth=3,markeredgecolor="yellow")
# linestyle or ls: ['solid' | 'dashed', 'dashdot', 'dotted' | (offset, on-off-dash-seq)
# | ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` | ``' '`` | ``''``]
# linewidth or lw: float value in points # alpha: float (0.0 transparent through 1.0 opaque) # marker: :mod:`A valid marker style <matplotlib.markers>`

Out[20]:

[<matplotlib.lines.Line2D at 0x900e7b8>]
Figure 17

Control over Axis Appearance

In [21]:

fig = plt.figure()ax = fig.add_axes([0,0,1,1])
ax.plot(x,y)
ax.plot(x,y,color='#FF8c00',linewidth =3,alpha=0.8904,linestyle='-', marker = 'o', markersize=20,markerfacecolor='blue',
markeredgewidth=3,markeredgecolor="yellow")
ax.set_xlim([0,1]) #Set the data limits for the x-axis
ax.set_ylim([0,2]) #Set the data limits for the y-axis
# linestyle or ls: ['solid' | 'dashed', 'dashdot', 'dotted' | (offset, on-off-dash-seq)
# | ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` | ``' '`` | ``''``]
# linewidth or lw: float value in points # alpha: float (0.0 transparent through 1.0 opaque) # marker: :mod:`A valid marker style <matplotlib.markers>`

Out[21]:

(0, 2)
Figure 18

For More refer to -

https://matplotlib.org/tutorials/introductory/sample_plots.html#sphx-glr-tutorials-introductory-sample-plots-py"

That’s it for today! I hope you learn something from this. Source code can be found on Github. I am happy to hear any questions or feedback.

Hope you like this article!! Don’t forget to like this article and share with others.

Buy now —

Thank You

Go Subscribe TheMenYouWantToBe

Show Some Love ❤

--

--