Python 3
Python 3
RV College of
Engineering
Dept of Mech. Engg. Python for Mechanical Engineers
RV College of Go, change the world
Engineering
Course Content
Introduction to Plotting and Visualization,
Matplot functions,
Seaborn
Solving Dynamic Equations,
Curve Fitting and Regression,
Understanding Iterative Solvers,
Data Analysis,
Programs on simple equation of Mechanics,
Mechanical vibration, thermal, heat transfer and fluid mechanics
RV College of Go, change the world
Engineering Data Visualisation
Data visualization is a way to represent information graphically, highlighting patterns and
trends in data and helping the reader to achieve quick insights.
Data visualization is the graphical representation of different pieces of information or
data, using visual elements such as charts, graphs, or maps.
Python provides various libraries that come with different features for visualizing data. All
these libraries come with different features and can support various types of graphs. In this
tutorial, we will be discussing four such libraries.
Matplotlib
Seaborn
Bokeh
Plotly
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Pyplot
Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported under
the plt alias:
E.g. Draw a line in a diagram from position (0,0) to position (6,250):
plt.plot(xpoints, ypoints)
plt.show() plt.plot(xpoints, ypoints, 'o')
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Plotting x and y points
The plot() function is used to draw points (markers) in a diagram.
By default, the plot() function draws a line from point to point.
The function takes parameters for specifying points in the diagram.
Parameter 1 is an array containing the points on the x-axis.
Parameter 2 is an array containing the points on the y-axis.
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Markers Shape
You can use the keyword argument marker to emphasize each point with a specified marker:
Marker Description
'o' Circle 'p' Pentagon plt.plot(ypoints, 'o:r')
'*' Star 'H' Hexagon plt.show()
'.' Point 'h' Hexagon
',' Pixel 'v' Triangle Down
'x' X '^' Triangle Up
'X' X (filled) '<' Triangle Left
'+' Plus '>' Triangle Right
'P' Plus (filled) '1' Tri Down
's' Square '2' Tri Up
'D' Diamond '3' Tri Left
'd' Diamond (thin) '4' Tri Right
'_' Hline '|' Vline
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Format Strings fmt
You can use also use the shortcut string notation parameter to specify the marker.
Line Reference
Line Syntax Description
'-' Solid line
':' Dotted line
'--' Dashed line
'-.' Dashed/dotted line
plt.plot(ypoints, 'X--g')
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Markers
You can use the keyword argument marker to emphasize each point with a specified marker:
plt.plot(ypoints, 'X-.b')
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Markers
You can use the keyword argument marker to emphasize each point with a specified marker:
plt.plot(ypoints, 'om--')
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Marker Size
You can use the keyword argument markersize or the shorter version, ms to set the size of the markers:
# Multiple lines
xpoints = np.array([0,2,4,6])
ascast = np.array([27,25,24,25])
forged1= np.array([23,21,20,27])
forged2 = np.array([20,18,17,16])
forged3=np.array([19,17,16,21])
plt.plot(xpoints, ascast)
plt.plot(xpoints, forged1)
plt.plot(xpoints, forged2)
plt.plot(xpoints, forged3)
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Create Labels for a Plot
With Pyplot, you can use the xlabel() and ylabel() functions to set a label for
the x- and y-axis.
plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")
plt.title("Computer")
plt.plot(xpoints, ascast)
plt.plot(xpoints, forged1)
plt.plot(xpoints, forged2)
plt.plot(xpoints, forged3)
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Set Font Properties for Title and Labels
You can use the fontdict parameter in xlabel(), ylabel(), and title() to set
font properties for the title and labels.
.
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Display Multiple Plots
With the subplot() function you can draw multiple plots in one figure:
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([0,2,4,6])
ascast = np.array([27,25,24,25])
plt.subplot (2,1,1)
plt.plot(xpoints, ascast)
.
xpoints = np.array([0,2,4,6])
forged1= np.array([23,21,20,27])
plt.subplot(2,1,2)
plt.plot(xpoints, forged1)
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Draw more than three plots: :
xpoints = np.array([0,2,4,6])
ascast = np.array([27,25,24,25])
forged1= np.array([23,21,20,27])
forged2 = np.array([20,18,17,16])
forged3=np.array([19,17,16,21])
plt.subplot (2,3,1)
plt.plot(xpoints, ascast)
plt.title('AsCast ')
plt.subplot (2,3,2)
plt.plot(xpoints, forged1)
plt.title('Forged-1')
. plt.subplot (2,3,3)
plt.plot(xpoints, forged2)
plt.title('Forged-2')
plt.subplot (2,3,4)
plt.plot(xpoints, forged2)
plt.title('Forged-3')
Super Title; You can add a title to the entire figure with the suptitle() function:
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Super Title; You can add a title to the entire figure with the suptitle() function:
plt.subplot (2,3,3)
plt.plot(xpoints, forged2)
plt.title('Forged-2')
plt.subplot (2,3,4)
plt.plot(xpoints, forged2)
plt.title('Forged-3')
plt.suptitle("Experimental Results")
.
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Matplotlib Scatter: With Pyplot, you can use the scatter() function to draw a scatter plot.
The scatter() function plots one dot for each observation. It needs two arrays of the same length, one
for the values of the x-axis, and one for values on the y-axis:
.
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Color Each Dot
You can even set a specific color for each dot by using an array of colors as value for
the c argument:
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
colors =
.np.array(["red","green","blue","yellow","pink","black","orange","purple","beige","brown","gray",
"cyan","magenta"])
plt.scatter(x, y, c=colors)
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
ColorMap
The Matplotlib module has a number of available colormaps.
A colormap is like a list of colors, where each color has a value that ranges from 0 to 100.
Here is an example of a colormap:
import matplotlib.pyplot as plt
import numpy as np
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
. colors = np.array([0, 10, 20, 30, 40, 45, 50, 55, 60, 70, 80, 90, 100])
plt.colorbar()
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Size
You can change the size of the dots with the s argument.
Just like colors, make sure the array for sizes has the same length as the arrays for the x- and y-axis:
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
. sizes = np.array([20,50,100,200,500,1000,60,90,10,300,600,800,75])
plt.scatter(x, y, s=sizes)
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Alpha
You can adjust the transparency of the dots with the alpha argument.
Just like colors, make sure the array for sizes has the same length as the arrays for the x- and y-axis:
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
.
sizes = np.array([20,50,100,200,500,1000,60,90,10,300,600,800,75])
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Combine Color Size and Alpha
You can combine a colormap with different sizes on the dots. This is best visualized if the dots are
transparent:
import matplotlib.pyplot as plt
import numpy as np
x = np.random.randint(100, size=(100))
y = np.random.randint(100, size=(100))
colors = np.random.randint(100, size=(100))
. sizes = 10 * np.random.randint(100, size=(100))
plt.colorbar()
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Matplotlib Bars
Creating Bars: With Pyplot, you can use the bar() function to draw bar graphs
Horizontal Bars
If you want the bars to be displayed horizontally instead of vertically, use the barh() function
plt.barh(x, y, color='red')
plt.show()
.
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Bar Width
The bar() takes the keyword argument width to set the width of the bars:
plt.bar(x, y, width=0.5)
plt.show()
Bar Height
The bar() takes the keyword argument width to set the width of the bars:
.
plt.barh(x, y, height=0.5)
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Matplotlib Histograms Histogram
A histogram is a graph showing frequency distributions.
It is a graph showing the number of observations within each given interval.
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
x = [21,22,23,4,5,6,77,8,9,10,31,32,33,34,35,36,37,18,49,50,100]
num_bins = 5
.n, bins, patches = plt.hist(x, num_bins, facecolor='red', alpha=0.75)
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
# example data
mu = 100 # mean of distribution
sigma = 15 # standard deviation of distribution
x = mu + sigma * np.random.randn(10000)
num_bins = 20
# the histogram of the data
.
n, bins, patches = plt.hist(x, num_bins, facecolor='blue', alpha=0.5)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
.
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib-PieChart
mport matplotlib.pyplot as plt
import numpy as np
.
import matplotlib.pyplot as plt
import numpy as np
y = np.array([35, 25, 25, 15])
mylabels = ["Apples", "Bananas", "Cherries", "Dates"]
myexplode = [0.2, 0, 0, 0]
plt.pie(y, labels =mylabels,explode = myexplode)
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib-PieChart
import matplotlib.pyplot as plt
import numpy as np
y = np.array([35, 25, 25, 15])
mylabels = ["Apples", "Bananas", "Cherries", "Dates"]
mycolors = ["black", "hotpink", "b", "#4CAF50"]
plt.pie(y, labels =mylabels, colors =mycolors)
plt.show()
.
RV College of Go, change the world
Engineering Data Visualisation-Seaborn
Create a scatter plot
Scatter plots are useful to show relationships between numeric
variables.
import
. seaborn as sns
import matplotlib.pyplot as plt
age = [10,12,15,16,17,17,20,25,30,35,37,39,40,42,45,50]
height = [120,130,145,143,182,186,170,172,172,182,178,168,182,187,160,166]
.sns.scatterplot(x=age, y=height)
plt.xlabel('age')
plt.ylabel('height')
plt.title('Height vs age')
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Seaborn
Create a Count plot
Count plots are useful to show relationships between categorical
variables.
import seaborn as sns
import matplotlib.pyplot as plt
colors = ['Blue','Blue','Red','Red','Red','Yellow','Yellow','Yellow','Yellow','Yellow']
sns.countplot(x=colors)
.plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Seaborn
Use Seaborn with Pandas
You can use seaborn with Pandas dataframes quite easily using the data
df = pd.read_csv('C:\\Users\\KRISHNA M\\Desktop\\kri1.csv')
print (df)
.sns.countplot(x='Duration', data=df)
RV College of Go, change the world
Engineering Data Visualisation-Seaborn
Add a Third Variable with Hue
You can add more than two variables to a seaborn visualization by
using the hue keyword
import seaborn as sns
data = sns.load_dataset('iris')
sns.scatterplot(x='sepal_length',
y='sepal_width',
data=data,
. hue='species')
RV College of Go, change the world
Engineering Data Visualisation-Seaborn
Create a lineplot with Seaborn
Often, you will need to work with dates. One of the most useful
data visualizations for dates is the line plot.
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
df = sns.load_dataset('flights')
print (df)
. f_1960 = df[df['year'] == 1960]
sns.relplot(x='month',y='passengers',
data=f_1960,
kind='line')
plt.xticks(rotation=90)
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Seaborn
Boxplots are useful to show the distribution of quantitative data
across categorical variables.
Understand the boxplot.
box: 25th to 75th percentile
middle line: median
whiskers: spread of distribution.
points: outliers
import matplotlib.pyplot as plt
import seaborn as sns
.
tips = sns.load_dataset('tips')
g = sns.catplot(x='sex', y='tip',
data=tips,
kind='box')
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Seaborn
Displot
Let’s recreate our normal distribution graph, this time using Seaborn distplot.
import numpy as np
normal_matrix =np.random.rand(100,1000)
matrix_sum = np.sum(normal_matrix,0)
sns.distplot(matrix_sum, kde=True)
.
RV College of Go, change the world
Engineering Data Visualisation-Seaborn
Curve fitting is a type of optimization that finds an optimal set of parameters for a defined
function that best fits a given set of observations.
Single Input
Two input
a line mapping function for two input variables may look as follows:
. Z = aX +bY +C where X and Y inputs, Z is out put and a,b& c are constants
.
RV College of
Engineering Curve fitting Go, change the world
popt, _ = sc.optimize.curve_fit(map, x, y)
a, b, c = popt
print ('Curve fitting equaiton y= {0}x2+{1}x+{2}'.format(a,b,c))
y_new = map(x, a, b, c)
. plt.scatter (x,y)
plt.plot(x,y_new, '--', color='red')
. plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.show()
RV College of
Engineering Curve fitting Go, change the world
Solve the following system of linear equations using Iterative solver method, use a pre-defined
threshold 𝜖=0.01 Do remember to check if the converge condition is satisfied or not.
x1,x2,x3 = 0,0,0
epsilon =0.01
converge =False
x_old = np.array([x1, x2, x3])
import sympy as sp
x = sp.Symbol('x')
y =sp.Symbol ('y')
p = x**2+x-6
eq = sp.Eq(p,0)
sol = sp.solve (eq, x)
print (sol)
.
RV College of
Engineering Data Analysis Go, change the world