Python Tutorial: Data Visualization (matplotlib)

python data visualization

Data Visualization is viewed by many disciplines as a modern equivalent of visual communication. Python has many libraries for data visualization, such as MatplotlibSeabornBokeh, Plotly, pygal, and etc. In this post, you will learn how to create basic visualization plots (Bar Chart, Pie Chart, Histogram, 2D Scatter plot, 3D Scatter plot, Live data visualization, and etc) using Matplotlib Python library.

Examples of data visualization techniques: Bar chart, Pie chart, Histogram, Scatter plot (2D and 3D), Treemap, Heatmap, and etc

1) What is Python?

Python is a scripting language and that is used for creating engineering-analysis tools, web development (server-side), software development, system scripting, and animation software. It designed by Guido van Rossum and first released in 1991. It’s an interpreted, High-level. General-purpose language. Python runs on Windows, Mac OS, and Linux.

Python Tutorial: Introduction for Beginners (Part 1)
Python Tutorial: Introduction for Beginners (Part 2)
SQL Tutorial: Introduction for beginners (Basic)
Python Tutorial: How to Connect MySQL Database in Python
Python Tutorial: Python GUI Programming (Tkinter)
Python Tutorial: Send Emails Using Python

Installation – Matplotlib 

Matplotlib – It is the oldest and most widely used library for data visualization in python. It created by John Hunter. Matplotlib was the first data visualization library

python data visualization
pip install matplotlib

pip install numpy

Import

import matplotlib.pyplot as plt

Python Data visualization – Getting Started

Plotting a Line (x)

python data visualization
import matplotlib.pyplot as plt

plt.plot([1, 2, 3]) #values 
plt.ylabel('Y - axis') #labels
plt.show()

Plotting a Line (x, y)

python data visualization
import matplotlib.pyplot as plt

x = [1, 2, 3] #X-AxisValues
y = [1, 3, 4] #Y-AxisValues
plt.plot(x, y)

plt.ylabel('Y - axis') 
plt.xlabel('X - axis') 
plt.show()

Plotting a Line (Adding a Title)

python data visualization
import matplotlib.pyplot as plt

x = [1, 2, 3]
y = [1, 3, 4]
plt.plot(x, y)

plt.ylabel('Y - axis') 
plt.xlabel('X - axis') 

plt.title('Hello World!') #title
plt.show()

Plotting a Line (More Lines on Same Plot )

python data visualization
import matplotlib.pyplot as plt 
  
#firstLineValues 
x1 = [1,2,3] 
y1 = [3,3,3] 
plt.plot(x1, y1) 
  
#secondLineValues 
x2 = [1,2,3] 
y2 = [2,6,2] 
plt.plot(x2, y2) 

#thirdLineValues 
x3 = [1,2,3] 
y3 = [1,1,4] 
plt.plot(x3, y3) 
  
plt.xlabel('x - axis') 
plt.ylabel('y - axis') 

plt.title('Three lines on the same graph') 

plt.show() 

Plotting a Line (Add a Legend)

python data visualization
import matplotlib.pyplot as plt 
  
#firstLineValues 
x1 = [1,2,3] 
y1 = [3,3,3] 
plt.plot(x1, y1, label="Line 1") 

#secondLineValues 
x2 = [1,2,3] 
y2 = [2,6,2] 
plt.plot(x2, y2, label="Line 2") 

#thirdLineValues 
x3 = [1,2,3] 
y3 = [1,1,4] 
plt.plot(x3, y3, label="Line 3") 
  
plt.xlabel('x - axis') 
plt.ylabel('y - axis') 

plt.title('Three lines on the same graph with legend') 

plt.legend() #addLegend

plt.show() 

Formatting the plot style

color=‘green’ or color=‘#000000’ – (Line Color) Enter RGB Value or Color Name
linestyle=‘dashed’ (Line Style) – supported values are ‘-‘, ‘–‘, ‘-.’, ‘:’, ‘None’, ‘ ‘, , ‘solid’, ‘dashed’, ‘dashdot’, ‘dotted’
linewidth=1 (Line Width) Enter any Positive Value

python data visualization
import matplotlib.pyplot as plt 
  
#firstLineValues 
x1 = [1,2,3] 
y1 = [3,3,3] 
plt.plot(x1, y1, color="#000000", linestyle=":", linewidth=1) 

#secondLineValues 
x2 = [1,2,3] 
y2 = [2,6,2] 
plt.plot(x2, y2, label="Line 1", color="blue", linestyle="solid", linewidth=2) 

#thirdLineValues 
x3 = [1,2,3] 
y3 = [1,1,4] 
plt.plot(x3, y3, color="red", linestyle="--", linewidth=1) 
  
plt.xlabel('x - axis') 
plt.ylabel('y - axis') 

plt.title('Customized Plot') 

plt.legend() #addLegend

plt.show()

marker=’o’ (Marker Style) – supported values are “.”, “,”, “o”, “v”, “^”, “<““>”“s”“p”“8”“*” and more.
markerfacecolor=’blue’ or markerfacecolor=‘#000000’ – (Marker Face Color) Enter RGB Value or Color Name
markersize=1 (Marker Size) Enter any Positive Value

python data visualization
import matplotlib.pyplot as plt 
  
#firstLineValues 
x1 = [1,2,3] 
y1 = [3,3,3] 
plt.plot(x1, y1, color="Green", linestyle=" ", marker="o") 

#secondLineValues 
x2 = [1,2,3] 
y2 = [2,6,2] 
plt.plot(x2, y2, 'b*') #shortForm ('b*' = color="Blue", linestyle=" ", marker="*", markersize="2")

#thirdLineValues 
x3 = [1,2,3] 
y3 = [1,1,4] 
plt.plot(x3, y3, 'ro') #shortForm ('ro' = color="Red", linestyle=" ", marker="o")
  
plt.xlabel('x - axis') 
plt.ylabel('y - axis') 

plt.title('Customized Plot') 

plt.show()

Style

python data visualization
import numpy as np
import matplotlib.pyplot as plt

plt.style.use(['dark_background', 'ggplot', 'fast']) #Style

plt.plot(np.random.rand(10))
plt.xlabel('x - axis') 
plt.ylabel('y - axis') 


plt.show() 

Scatterplot

python data visualization
import matplotlib.pyplot as plt 
  
#firstLineValues 
x1 = [1,2,3,4,5,6,7,8,9,10] 
y1 = [3,3,3,3,3,3,3,3,3,3] 
plt.scatter(x1, y1) 

#secondLineValues 
x2 = [1,2,3,4,5,6,7,8,9,10] 
y2 = [2,6,2,5,5,5,5,8,3,5] 
plt.scatter(x2, y2) 

#thirdLineValues 
x3 = [1,2,3,4,5,6,7,8,9,10] 
y3 = [1,1,4,2,5,6,7,4,2,3] 
plt.scatter(x3, y3) 
  
plt.xlabel('x - axis') 
plt.ylabel('y - axis') 

plt.title('Scatterplot')

plt.show()

Connected Scatter plot

python data visualization
import matplotlib.pyplot as plt 
  
#firstLineValues 
x1 = [1,2,3,4,5,6,7,8,9,10] 
y1 = [3,3,3,3,3,3,3,3,3,3] 
plt.plot(x1, y1, 'ro', label="First", markersize="2", linestyle="solid") 

#secondLineValues 
x2 = [1,2,3,4,5,6,7,8,9,10] 
y2 = [2,6,2,5,5,5,5,8,3,5] 
plt.plot(x2, y2, 'go', label="Second", markersize="2", linestyle="solid") 

#thirdLineValues 
x3 = [1,2,3,4,5,6,7,8,9,10] 
y3 = [1,1,4,2,5,6,7,4,2,3] 
plt.plot(x3, y3, 'bo', label="Third", markersize="2", linestyle="solid") 
  
plt.xlabel('x - axis') 
plt.ylabel('y - axis') 

plt.title('Connected Scatter plot')

plt.legend()

plt.show() 

Bar Chart

python data visualization
import matplotlib.pyplot as plt 

x = [1, 2, 3, 4, 5, 6] #x-coordinates
height = [5, 20, 35, 22, 3, 1] #heightsOfBars (y)

barLabel = ['First', 'Second', 'Third', 'Fouth', 'Fifth', 'Sixeth'] #barLabels
barColor = ['#1abc9c', '#f1c40f', '#8e44ad', '#e74c3c', '#34495e', '#3498db'] #barColors

plt.bar(x, height, tick_label = barLabel , width = 0.5, color = barColor) 

plt.xlabel('x - axis') 
plt.ylabel('y - axis')

plt.title('Bar Chart') 

plt.show() 

Pie Chart

autopact – Used to format the value of each label — (autopct = ‘%1.2f%%’) – Two decimal Places

python data visualization
import matplotlib.pyplot as plt 
  
pieLabels = ['A', 'B', 'C', 'D', 'E', 'F'] #labels 
pieSlices = [13,4,8,6,9,7] #PortionCoveredbyEachLabel  
colors = ['#1abc9c', '#f1c40f', '#8e44ad', '#e74c3c', '#34495e', '#3498db'] #LabelColor
  
plt.pie(pieSlices, labels = pieLabels, colors=colors,
        startangle=90, explode = (0.1, 0.1, 0.1, 0.1, 0.1, 0.1),
        radius = 1.2, autopct = '%1.2f%%')

plt.title('Pie Chart') 
plt.show()

Histogram

python data visualization
import matplotlib.pyplot as plt

heights = [12,15,70,41,20,55,20,25,23,40,41, 
        70,1,2,45,5,7,84,10,57,18,10,7,32,11,20,47]

range = (0, 100) 
bins =  15

plt.hist(heights, bins, range, color = 'blue', 
        histtype = 'bar', rwidth = 0.8, density = True) 

plt.xlabel('Height (m)') 
plt.ylabel('Trees')

plt.title('Histogram')  
plt.show() 

Sub Plot

Method 1

python data visualization
import matplotlib.pyplot as plt 

labels = ['A', 'B', 'C', 'D', 'E', 'F']
values = [5, 10, 20, 50, 80, 100]


colors = ['#1abc9c', '#f1c40f', '#8e44ad', '#e74c3c', '#34495e', '#3498db']

#figsize = (width, height)
plt.figure(figsize=(9, 3))

#plt.subplot(nrows, ncols, index) all integers must be less than 10
plt.subplot(131) #1
plt.bar(labels, values, color = colors) #bar

plt.subplot(132) #2
plt.scatter(labels, values, color = colors) #scatter

plt.subplot(133) #3
plt.plot(labels, values, color = colors[0])#plot

plt.suptitle('Sub Plot')

plt.show()

Method 2

python data visualization
import matplotlib.pyplot as plt 

labels1 = ['A', 'B', 'C', 'D', 'E', 'F']
values1 = [5, 10, 20, 50, 80, 100]

labels2 = ['G', 'H', 'I', 'J', 'K', 'L']
values2 = [12, 20, 100, 90, 80, 80]


colors = ['#1abc9c', '#f1c40f', '#8e44ad', '#e74c3c', '#34495e', '#3498db']

fig = plt.figure()
  
plt1 = fig.add_subplot(221)
plt1.bar(labels1, values1, color = colors) #bar
plt1.set_title('SubPlot 1') 
  
plt2 = fig.add_subplot(222)
plt2.bar(labels2, values2, color = colors) #bar
plt2.set_title('SubPlot 2')

plt3 = fig.add_subplot(223)
plt3.bar(labels2, values2, color = colors) #bar
plt3.set_title('SubPlot 3') 
  
plt4 = fig.add_subplot(224)
plt4.bar(labels1, values1, color = colors) #bar
plt4.set_title('SubPlot 4') 
  
fig.subplots_adjust(hspace=0.5,wspace=0.5) #adjustingSubplotsSpaces
  
plt.show()

More details: https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.pyplot.subplot.html

Mathematical Equation – Linear, Quadratic, Cubic and Quartic

python data visualization
import matplotlib.pyplot as plt 
import numpy as np

x = np.arange(-10, 10, 0.1) #Genarate X

fig = plt.figure()
  
plt1 = fig.add_subplot(221)
plt1.plot(x, x, color='#1abc9c') #y = x
plt1.set_title('Linear (Y = X)') 
  
plt2 = fig.add_subplot(222)
plt2.plot(x, x**2, color='#f1c40f') #) # y = x**2
plt2.set_title('Quadratic ($Y = X^2$)') 
  
plt3 = fig.add_subplot(223)
plt3.plot(x, x**3, color='#8e44ad') #) #y = x**3
plt3.set_title('Cubic ($Y = X^3$)')

plt3 = fig.add_subplot(224)
plt3.plot(x, x**4, color='#e74c3c') #) #y = x**4
plt3.set_title('Quartic ($Y = X^4$)') 
  
fig.subplots_adjust(hspace=0.5,wspace=0.5) 
  
plt.show()

Mathematical Equation – Sin(x) and Cos(x)

python data visualization
import matplotlib.pyplot as plt 
import numpy as np

x = np.arange(-10, 10, 0.2) #Genarate X
sy = np.sin(x) #Genarate Y for Sin
cy = np.cos(x) #Genarate Y for Cos

fig = plt.figure()
  
plt1 = fig.add_subplot(211)
plt1.plot(x, sy, color='#1abc9c') #Sin(x)
plt1.set_title('sin (x)')
plt1.grid(True, which='major')
  
plt2 = fig.add_subplot(212)
plt2.plot(x, cy, color='#f1c40f') #) #Cos(x)
plt2.set_title('cos (x)')
plt2.grid(True, which='major')
  
fig.subplots_adjust(hspace=0.5,wspace=0.5) 
  
plt.show()

Scatter Plot  – 3D (x,y,z)

import

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
python data visualization
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

fig = plt.figure()
plt1 = fig.add_subplot(111, projection='3d')

xa =[0,1,3,5,7,8,4,5,7,9,8,2,4,7,8,5]
ya =[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
za =[0,1,4,7,8,4,5,6,9,7,1,2,1,5,4,7]

xb =[0,-1,-3,-5,-7,-8,-4,-5,-7,-9,-8,-2,-4,-7,-8,-5]
yb =[0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10,-11,-12,-13,-14,-15]
zb =[0,-1,-4,-7,-8,-4,-5,-6,-9,-7,-1,-2,-1,-5,-4,-7]

plt1.scatter(xa, ya, za, color='blue', marker='o')
plt1.scatter(xb, yb, zb, color='black', marker='o' )

plt1.set_xlabel('X-axis')
plt1.set_ylabel('Y-axis')
plt1.set_zlabel('Z-axis')

plt.show()

Connected Scatter Plot  – 3D (x,y,z)

python data visualization
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

fig = plt.figure()
plt1 = fig.add_subplot(111, projection='3d')

xa =[0,1,3,5,7,8,4,5,7,9,8,2,4,7,8,5]
ya =[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
za =[0,1,4,7,8,4,5,6,9,7,1,2,1,5,4,7]

xb =[0,-1,-3,-5,-7,-8,-4,-5,-7,-9,-8,-2,-4,-7,-8,-5]
yb =[0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10,-11,-12,-13,-14,-15]
zb =[0,-1,-4,-7,-8,-4,-5,-6,-9,-7,-1,-2,-1,-5,-4,-7]

plt1.plot(xa, ya, za, marker='o', color="green", linestyle="solid")
plt1.plot(xb, yb, zb, marker='o', color="black", linestyle="solid")

plt1.set_xlabel('X-axis')
plt1.set_ylabel('Y-axis')
plt1.set_zlabel('Z-axis')

plt.show()

Get Data from a File

python data visualization

Data.txt

0,0
1,1
2,5
3,0
4,0
5,1
6,0
7,0
8,9
9,4
10,10
11,3
12,9
13,1

Data_Visualization.py

import matplotlib.pyplot as plt

data = open("data.txt","r")
xdata = []
ydata = []

for line in data:
    x,y = data.readline().split(',')
    xdata.append(int(x))
    ydata.append(int(y))
    
plt.plot(xdata,ydata)
plt.show()

Live Updating Graphs – 1

import

import matplotlib.pyplot as plt
import matplotlib.animation as animation

import random
python data visualization
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
import random

fig = plt.figure()
plta = fig.add_subplot(1,1,1)
xdata = []
ydata = []


def animate(i):
    x = i #Genarate X (0,1,2,3,4,5,6)
    y = random.randint(0,10) #Genarate Y (Random Number 0 -10)
    xdata.append(int(x)) #Add X to list
    ydata.append(int(y)) #Add Y to list
    print(str(x) +" "+  str(y)) #Print X and Y
    plta.clear() 
    plta.plot(xdata,ydata) #Create a Plot
    
anims = animation.FuncAnimation(fig, animate, interval=1000) #Run animation
plt.show()

Live Updating Graphs – 2 (Using File)

python data visualization live data

genarate_data.py – Run this first

import random
import time

data = open("datas.txts","a")
data.write("0,0")
data.close()

for i in range(30):
    data = open("datas.txt","a")
    x = i+1
    y = random.randint(0,10)
    wr = (str(x)+","+str(y))
    data.write("\n"+wr)
    print(wr)
    time.sleep(1)
    data.close()

chart.py

import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig = plt.figure()
plta = fig.add_subplot(1,1,1)

def animate(i):
    data = open("datas.txt","r")
    xdata = []
    ydata = []
    for line in data:
        x,y = line.split(',') #Get X and Y data from list
        xdata.append(int(x)) #Add X to list
        ydata.append(int(y)) #Add Y to list
    plta.clear() 
    plta.plot(xdata,ydata) #Create a Plot
    plta.grid(True)

anims = animation.FuncAnimation(fig, animate, interval=1000) #Run animation
plt.show()

For more details: https://matplotlib.org/contents.html

Sources: 
https://pixabay.com (Images)
https://matplotlib.org/contents.html (Details)

Hi Guys,

Hope this post (Python Data Visualization) will help you to learn something. If you enjoy my work, please Share my posts with your friends and anyone who might be interested in programming. Don’t forget to Comment and, Subscribe.

See you in the comment section.

Like ctechf Facebook fan page : https://www.facebook.com/ctechf

Also Read :

How to be a Programmer

Leave a Reply

275 Shares
Share
Tweet
Share
Pin
Share