Introduction to Computational Physics
Data Visualisation
Dr. Sharad Chandra Tripathi
1/40
Data Visualisation
What is data visualisation?
Definition: Data visualization is the graphical representation of
information and data.
Importance: It helps to make complex data more accessible,
understandable, and usable.
Overview: Types: Charts; Bar Charts, Line Charts, Pie Charts,
Graphs, Maps, etc.
2/40
Bar Chart
A bar chart (or bar graph) is a visual representation of data
where individual bars represent the values of different
categories. It is used to compare quantities across different
categories or groups.
Figure: This is a sample Bar Chart.
3/40
Python Code for Sample Bar Chart
i
mport matplotlib . pyplot as plt
# Sample data
categories = [ ’A ’ , ’B ’ , ’C ’ , ’D ’]
values = [10 , 20 , 15 , 25]
plt . bar ( categories , values , color = ’ skyblue ’)
plt . xlabel ( ’ Categories ’)
plt . ylabel ( ’ Values ’)
plt . title ( ’ Bar Chart Example ’)
plt . show ()
4/40
Types of Bar Charts
Vertical Bar Chart
Bars extend vertically from the x-axis. It’s the most common type and
is used for comparing quantities across different categories.
Horizontal Bar Chart
Bars extend horizontally from the y-axis. It’s useful when category
names are long or when you have many categories.
Grouped Bar Chart
Shows bars for different sub-categories within each main category. This
allows for comparison between different sub-groups within each main
category.
Stacked Bar Chart
Displays bars stacked on top of each other. It shows the total size of
each category as well as the proportion of each sub-category.
5/40
Horizontal Bar Chart
Figure: This is a sample Horizontal Bar Chart.
6/40
Python Code for Horizontal Bar Chart
i
mport matplotlib . pyplot as plt
# Sample data
categories = [ ’A ’ , ’B ’ , ’C ’ , ’D ’]
values = [10 , 20 , 15 , 25]
plt . barh ( categories , values , color = ’ skyblue ’)
plt . xlabel ( ’ Values ’)
plt . ylabel ( ’ Categories ’)
plt . title ( ’ Horizontal Bar Chart Example ’)
plt . show ()
7/40
Grouped Bar Chart
Figure: This is a sample Grouped Bar Chart.
8/40
Python Code for Grouped Bar Chart
i
mport matplotlib . pyplot as plt
import numpy as np
# Sample data
categories = [ ’A ’ , ’B ’ , ’C ’ , ’D ’]
values1 = [10 , 20 , 15 , 25] # First group of
values
values2 = [12 , 22 , 17 , 27] # Second group of
values
# Number of categories
n = len ( categories )
# Define the positions for the bars
x = np . arange ( n )
width = 0.35 # Width of the bars
9/40
...continued (Python Code for Grouped Bar Chart)
# Create the plot
fig , ax = plt . subplots ()
# Plotting the bars for the first group
bars1 = ax . bar ( x - width /2 , values1 , width ,
label = ’ Group 1 ’ , color = ’ skyblue ’)
# Plotting the bars for the second group
bars2 = ax . bar ( x + width /2 , values2 , width ,
label = ’ Group 2 ’ , color = ’ salmon ’)
# Add labels , title , and legend
ax . set_xlabel ( ’ Categories ’)
ax . set_ylabel ( ’ Values ’)
ax . set_title ( ’ Grouped Bar Chart Example ’)
ax . set_xticks ( x )
ax . set_xticklabels ( categories )
ax . legend ()
# Show the plot
plt . show ()
10/40
Stacked Bar Chart
Figure: This is a sample Stacked Bar Chart.
11/40
Python Code for Stacked Bar Chart
i
mport matplotlib . pyplot as plt
import numpy as np
# Sample data
categories = [ ’A ’ , ’B ’ , ’C ’ , ’D ’]
values1 = [10 , 20 , 15 , 25] # First group of
values
values2 = [5 , 10 , 10 , 20] # Second group of
values
# Number of categories
n = len ( categories )
# Define the positions for the bars
x = np . arange ( n )
width = 0.5 # Width of the bars
# Create the plot
fig , ax = plt . subplots ()
12/40
...continued (Python Code for Stacked Bar Chart)
# Plotting the bars for the first group
bars1 = ax . bar (x , values1 , width , label = ’ Group
1 ’ , color = ’ skyblue ’)
# Plotting the bars for the second group on top
of the first group
bars2 = ax . bar (x , values2 , width ,
bottom = values1 , label = ’ Group 2 ’ ,
color = ’ salmon ’)
# Add labels , title , and legend
ax . set_xlabel ( ’ Categories ’)
ax . set_ylabel ( ’ Values ’)
ax . set_title ( ’ Stacked Bar Chart Example ’)
ax . set_xticks ( x )
ax . set_xticklabels ( categories )
ax . legend ()
# Show the plot
plt . show ()
13/40
Line Chart
Figure: This is a sample Line Chart.
14/40
Python Code for Line Chart
i
mport matplotlib . pyplot as plt
# Sample data
years = [2020 , 2021 , 2022 , 2023]
values = [100 , 150 , 200 , 250]
plt . plot ( years , values , marker = ’o ’ ,
linestyle = ’ - ’ , color = ’ green ’)
plt . xlabel ( ’ Year ’)
plt . ylabel ( ’ Values ’)
plt . title ( ’ Line Chart Example ’)
plt . show ()
15/40
Pie Chart
Figure: This is a sample Pie Chart.
16/40
Python Code for Pie Chart
i
mport matplotlib . pyplot as plt
# Sample data
labels = [ ’A ’ , ’B ’ , ’C ’ , ’D ’]
sizes = [20 , 30 , 25 , 25]
plt . pie ( sizes , labels = labels , autopct = ’ %1.1 f %% ’ ,
startangle =140 ,
colors =[ ’# ff9999 ’ , ’ #66 b3ff ’ , ’ #99 ff99 ’ ,
’# ffcc99 ’ ])
plt . title ( ’ Pie Chart Example ’)
plt . show ()
17/40
Scatter Plot
Figure: This is a sample Scatter Plot.
18/40
Python Code for Scatter Plot
i
mport matplotlib . pyplot as plt
# Sample data
x = [1 , 2 , 3 , 4 , 5]
y = [10 , 20 , 15 , 25 , 30]
plt . scatter (x , y , color = ’ red ’)
plt . xlabel ( ’X Axis ’)
plt . ylabel ( ’Y Axis ’)
plt . title ( ’ Scatter Plot Example ’)
plt . show ()
19/40
Understanding 3D Data
Explanation of 3D data visualization (3D plots, surfaces).
Examples: 3D scatter plots, surface plots.
Benefits: Revealing complex relationships, better for spatial data.
20/40
3D Scatter Plots
Description and use cases.
Example: Visualizing relationships between three variables.
Figure: Example of a 3D scatter plot.
21/40
Python Code for 3D Scatter Plot
import matplotlib . pyplot as plt
from mpl_toolkits . mplot3d import Axes3D
import numpy as np
# Generate sample data
np . random . seed (0) # For reproducibility
x = np . random . rand (100)
y = np . random . rand (100)
z = np . random . rand (100)
colors = np . random . rand (100) # Color by an
additional variable
sizes = 50 * np . random . rand (100) # Size of the
points
22/40
...continued (Python Code for 3D Scatter Plot)
# Create a 3 D scatter plot
fig = plt . figure ( figsize =(10 , 7) )
ax = fig . add_subplot (111 , projection = ’3 d ’)
# Plot data
sc = ax . scatter (x , y , z , c = colors , s = sizes ,
cmap = ’ viridis ’ , alpha =0.6 , edgecolors = ’w ’ ,
linewidth =0.5)
# Set labels and title
ax . set_title ( ’3 D Scatter Plot ’)
ax . set_xlabel ( ’X - axis ’)
ax . set_ylabel ( ’Y - axis ’)
ax . set_zlabel ( ’Z - axis ’)
23/40
...continued (Python Code for 3D Scatter Plot)
# Add color bar
cbar = plt . colorbar ( sc , ax = ax , pad =0.1)
cbar . set_label ( ’ Color Scale ’)
# Save the plot
plt . savefig ( ’3 d_scatter_plot . png ’ , dpi =300)
# Show the plot
plt . show ()
24/40
3D Surface Plots
Description and use cases.
Example: Showing topography or a surface of values.
Figure: Example of a 3D surface plot.
25/40
Python Code for 3D Surface Plot
import matplotlib . pyplot as plt
from mpl_toolkits . mplot3d import Axes3D
import numpy as np
# Generate sample data
x = np . linspace ( -5 , 5 , 100)
y = np . linspace ( -5 , 5 , 100)
x , y = np . meshgrid (x , y )
z = np . sin ( np . sqrt ( x **2 + y **2) ) # Function for
surface plot
# Create a 3 D surface plot
fig = plt . figure ( figsize =(10 , 7) )
ax = fig . add_subplot (111 , projection = ’3 d ’)
# Plot data
surf = ax . plot_surface (x , y , z , cmap = ’ viridis ’ ,
edgecolor = ’ none ’)
26/40
...continued (Python Code for 3D Surface Plot)
# Set labels and title
ax . set_title ( ’3 D Surface Plot ’)
ax . set_xlabel ( ’X - axis ’)
ax . set_ylabel ( ’Y - axis ’)
ax . set_zlabel ( ’Z - axis ’)
# Add color bar
cbar = plt . colorbar ( surf , ax = ax , pad =0.1)
cbar . set_label ( ’ Color Scale ’)
# Save the plot
plt . savefig ( ’3 d_surface_plot . png ’ , dpi =300)
# Show the plot
plt . show ()
27/40
Comparative Analysis
Discuss when to use 2D vs. 3D visualization.
Benefits and limitations of each type.
Example scenarios where one is preferred over the other.
28/40
2D Visualization
Benefits:
Simplicity: Easier to create and interpret, especially for simple
datasets.
Clarity: Often clearer for representing data with fewer dimensions.
Performance: Requires less computational power and is faster to
render.
Accessibility: More accessible for audiences not familiar with 3D
concepts.
Limitations:
Limited Data Representation: May not effectively represent complex
datasets.
Less Immersive: Does not provide a sense of depth or spatial
relationships.
29/40
Example Scenario: Projectile Motion
Dataset: Trajectory of a projectile, including time, horizontal distance,
and vertical distance.
Visualization: A 2D plot of vertical distance vs. horizontal distance.
Use Case: Effective for understanding the path of the projectile and
comparing different parameters.
30/40
Projectile Motion
Figure: Example of a 2D Projectile Motion Plot.
31/40
Python Code to Generate Projectile Motion
import numpy as np
import matplotlib . pyplot as plt
# Constants
g = 9.8 # Acceleration due to gravity ( m / s ^2)
v0 = 50 # Initial velocity ( m / s )
angle = 45 # Launch angle ( degrees )
# Convert angle to radians
angle_rad = np . radians ( angle )
# Time of flight
t_flight = 2 * v0 * np . sin ( angle_rad ) / g
# Time array
t = np . linspace (0 , t_flight , num =500)
32/40
...continued (Python Code to Generate Projectile Motion)
# Equations of motion
x = v0 * np . cos ( angle_rad ) * t
y = v0 * np . sin ( angle_rad ) * t - 0.5 * g * t **2
# Plotting
plt . figure ( figsize =(10 , 6) )
plt . plot (x , y , label = ’ Trajectory of the
projectile ’ , color = ’b ’)
plt . title ( ’ Projectile Motion : Vertical Distance
vs . Horizontal Distance ’)
# Add description of initial values
description = ( f ’ Initial Velocity : { v0 } m / s \ n ’
f ’ Launch Angle : { angle } degrees \ n ’
f ’ Gravity : { g } m / s ^2 ’)
33/40
...continued (Python Code to Generate Projectile Motion)
# Annotate initial values above the title
plt . annotate ( description ,
xy =(0.15 , 0.8) , # Position of the
text (x , y ) in normalized
coordinates
xycoords = ’ axes fraction ’ ,
fontsize =12 ,
ha = ’ center ’ , # Horizontal alignment
bbox = dict ( boxstyle = " round , pad =0.3 " ,
edgecolor = " black " ,
facecolor = " lightgray " ) )
plt . xlabel ( ’ Horizontal Distance ( m ) ’)
plt . ylabel ( ’ Vertical Distance ( m ) ’)
plt . grid ( True )
plt . legend ()
plt . show ()
34/40
3D Visualization
Benefits:
Comprehensive Representation: Allows for representation of three
dimensions.
Enhanced Insight: Provides an intuitive grasp of spatial structures
and dynamics.
Interactivity: Supports interactive exploration, such as rotation and
zooming.
Limitations:
Complexity: More complex to create and interpret; requires careful
design.
Computational Resources: Requires more power and may be slower to
render.
Depth Perception: Can introduce challenges related to spatial
understanding.
35/40
Example Scenario: Magnetic Field Data
Dataset: Magnetic field distribution around a magnet, including spatial
coordinates and field strength.
Visualization: A 3D vector field plot or 3D surface plot showing the
magnetic field.
Use Case: Helps visualize spatial variation of the magnetic field, crucial
for designing devices or understanding field effects.
36/40
Magnetic Field around a Simple Bar Magnet
Figure: Example of a 3D Magnetic Fields.
37/40
Practical Examples in Physics
2D Visualization:
Dataset: Temperature vs. time from a cooling experiment.
Visualization: Line graph showing the cooling curve.
Use Case: Easy to understand how temperature changes over time.
3D Visualization:
Dataset: Distribution of electron density in an atom or molecule.
Visualization: 3D contour plot or isosurface of electron density.
Use Case: Visualizes spatial distribution of electrons, important for
understanding chemical bonding and electronic structure.
38/40
Popular Python Libraries for Visualization
Matplotlib: Basic plotting.
Step-by-step procedure for solving a problem
Seaborn: Statistical data visualization.
Visual representation of an algorithm
Common flowchart symbols
Plotly: Interactive plots.
Simple example to demonstrate algorithm and flowchart creation
Altair: Declarative statistical visualization.
Simple example to demonstrate algorithm and flowchart creation
39/40
Tips for Effective Data Visualization
Choose the right type of visualization.
Keep it simple and uncluttered.
Use color effectively.
Provide context and labels.
40/40