Welcome to Engineering Python.
This is a Python programming course for engineers.
The MatPlotLib gallery is a showcase of hundreds of sample figures.
Each figure comes with its source code.
In this video, I will talk about some of the most commonly used gallery examples.
Before we start, we need to turn on the Jupyter notebook renderer so we can see all the plotting
results in this browser.
We need to import pyplot as plt.
We also need to import numpy as np.
In the first figure, we will create a vertical bar chart.
Let's first generate some data points.
X is a NumPy array that contains 7 integer numbers from 0 to 6.
Y is the sine values of these numbers.
Y's values are between -1 and +1.
Next, we create a figure.
5 inches by 4 inches.
The dpi is 80.
Then, we use the bar function and X, Y as arguments to plot the bar chart.
For each of these 7 bars, we first check if the Y value is greater than or equal to 0.
If yes, we put Y's value as text on top of the bar.
This is the text's location in the figure.
Note that the Y location is offset by 0.05 so it doesn't overlap with the bar.
We show only two digits after the decimal points.
The text is centered horizontally.
If the Y value is less than 0, then we put Y's value as text below the bar.
This is the text's location in the figure.
Note that the Y location is offset by -0.1 so it does not overlap with the bar.
We show only two digits after the decimal points.
The text is centered horizontally.
Next, we set y limits to -1.1 and 1.1.
These limits will allow extra margin for showing the text on top and at the bottom of the bars.
After that, we remove all the xticks and yticks because we don't need such information.
Finally, we show the figure on the computer screen.
The result is in Figure 1.
In the second figure, we will create a horizontal bar chart.
We first define a list named cities.
It contains three cities' names, New York City, Los Angeles, and Chicago.
These are the three largest cities in the United States.
Next, we generate 3 integer numbers.
They will be the indexes of these three cities.
This is the wind speed measurements in three cities.
The average wind speeds are 10 miles per hour in New York City, 5 miles per hour in Los
Angeles, and 13 miles per hour in Chicago.
This is the measurement error tolerance.
Plus or minus 3 miles per hour for New York City, plus or minus 1 mile per hour for Los
Angles, and plus or minus 2 miles per hour for Chicago.
Next, we create a figure.
And then use the barh function to create a horizontal barchart.
The first two arguments are the city indexes and the wind speeds.
This xerror is the measurement error tolerance.
alpha equals 50% means the bars are half transparent.
yticks will put the city names at these locations.
x label will be wind speed.
We also add a title, average wind speed at three cities.
The result is shown in Figure 2.
Boxplots can be used to show two or more groups of random test data.
In this example, I create two random data samples.
The first sample contains 30 data points.
They come from a normal distribution with a mean 0 and the standard deviation 1.
The second sample contains 30 data points.
They come from a normal distribution with a mean 3 and the standard deviation 2.
Next, we create the figure, and then use the boxplot function to show these two data samples.
The top of this bar means 100th percentile.
here is the 75th percentile, here is the median, which is the 50th percentile, this is the
25th percentile, and this is the 0th percentile.
The mean is marked by a triangle.
xticks display the names of these two data samples, 1 and 2.
The result is shown in Figure 3.
In the fourth example, we will create a pie chart.
labels are the slice names.
We have apples, bananas, pears, and oranges.
sizes are the weights of these fruits, 25 pounds, 30 pounds, 50 pounds, and 60 pounds.
colors are the colors of these fruits, darkred, gold, greenyellow, and darkorange.
explode is a tuple.
Only the second value is non-zero.
So, it only explodes the 2nd slice, which is bananas.
Next, we create the figure, and use the pie function to create the pie chart.
The first argument will be the sizes.
Then we pass other arguments like the explode, the labels, the colors, and show the shadow.
The slices will be plotted counter-clockwise, starting from angle 0, which is here.
We show the relative numbers in percentage, instead of the real weights of the fruits.
We also keep one digit after the decimal point.
We set the axis aspect ratio to be equal so the pie is a circle.
Otherwise, it may appear to be an ellipse.
The result is shown in Figure 4.
In the next example, we will plot a histogram.
First, let's generate a large sample with 10,000 numbers.
The numbers come from a normal distribution with mean mu equals 100 and standard deviation
sigma equals 15.
We use 30 bins to show the histogram.
Next, we create the figure and use the hist function to plot the histogram.
x is the sample of 10,000 random numbers, this is the number of bins, the color of the
bins is green, the edge color of the bins is black.
alpha equals 50%.
It means the bins are half transparent.
We set the xlabel, the ylabel, and the title.
The title is rendered using the LaTeX expressions so it will show the Greek letters mu and sigma.
The result is in Figure 5.
MatPlotLib can create 3D images.
This figure is a brief illustration of the 3D viewpoint.
This is the object.
This is the viewer.
Elevation refers to the angle between the eye viewing direction towards the object and
the horizontal x-y plane.
It is the up-down angle.
Azimuth refers to the rotation of the viewer around a vertical axis.
It is the side to side angle.
With that knowledge, let's take a look at this 3D wireframe example.
We need to import this axes3d module for all the 3D plotting.
After we create a figure, we add a single subplot.
We need to specify the projection to be 3d.
Next, we get some test data from this module and give them to X, Y, and Z.
If you want, you can print out these values and see what they are.
After that, we plot the wireframe using the data X, Y, and Z.
We don't want to plot every data point in the test data.
Otherwise, the image will be too dense.
rstride and cstride control the row and col step sizes.
We plot every 5th row and column.
The view_init function controls the view point.
The azimuth is 170 degrees and the elevation is 30 degrees.
The result is shown in Figure 6.
Before we proceed to the next example, we need to talk about a concept called meshgrid.
Let's first create variables x and y. x contains three numbers 0, 0.5, and 1.
y contains two numbers 0 and 1.
Note that they are both 1D arrays.
NumPy dot meshgrid with x and y as arguments will create xmesh and ymesh, both are 2D arrays.
If we specify sparse to be True, xmesh is 1 row by 3 column 2D array, and ymesh is 2
row by 1 column 2D array.
If we do not specify the sparse parameter, then xmesh and ymesh are both 2 row by 3 column
2D arrays.
xmesh is stretched vertically, and ymesh is stretched horizontally so their shapes match.
After all these preparations, let's proceed to this 3D surface example.
Create a figure.
Set the current axes projection to 3d.
Generate the data points for X.
The data points spread between -5 and 5 with a step of 0.25.
Use the same method to generate data points for Y.
Update X and Y using their mesh values.
Calculate the sine values of the square toot of x squared plus y squared and give them
to Z.
These are element-wise operations.
So, Z is also a 2D array and has the same shape as X and Y.
Next, we use the plot surface function and X, Y, Z as the arguments.
rstride and cstride are both 1.
That means, we plot every row and every column.
We use coolwarm colormap so that small values are denoted by the blue or cool color and
large values are denoted by the red or warm color.
The line width is set to 0.2, which is very thin, the line color is black.
Z limits are set to -1.01 and 1.01.
So, we make sure no part of the figure is cut off and we have a very small margin.
We associate the colorbar with the surface we just created.
The shrink value is the fraction by which to shrink the colorbar height.
In this case, the colorbar height is 50% of the total height of the figure from the bottom
to the top.
The aspect value specifies the ratio of height to width.
In this case, the height is 5 times as long as the width.
The result is shown in Figure 7.
MatPlotLib can create 2D and 3D animations.
We will demonstrate the next several examples in the command prompt or terminal because
there is a known bug in MatPlotLib version 2.1.0 that may cause an error if we run these
programs directly in Jupyter Notebook.
This is the version I am current using.
This bug may be fixed by a future MatPlotLib release.
The source code of the 2D animation is in this file.
Let's open this file in the Jupyter editor.
In this example, we need to import numpy, pyplot, and animation modules into our program.
We create a NumPy array x, which contains data points from 0 to 2 pi, with a step of
0.1.
Next, we create a figure, and use the plot function to return a list of two lines, one
is the sine function, another is the cosine function.
This statement will create the indexes of 20 picture frames.
We have to define our own animate function to specify what will happen during each picture
frame.
The parameter i is the frame index.
For each frame, we will update line 0, which is the sine curve, using this formula.
We will do the same for line 1, which is the cosine curve.
After that, the updated lines are returned and they will be used in the animation module's
FuncAnimation function to redraw each picture frame.
In this FuncAnimation function, the figure is the figure window we just created, func
is the animate function we just defined, frames are the 20 picture frame indexes, interval
equals 100 milliseconds, which is the time interval between two picture frames.
After the 20 picture frames are done, we don't want to repeat.
So, repeat equals False.
Let's run this animation_2d.py file in a command window.
In the command window, I first change directory to this folder where I store the Python file.
Then I type in python animation_2d.py, I can see the animation now.
The next example is a 3D animation.
The source code is in this file.
Let's open it in the Jupyter editor.
In this example, we need to import numpy, pyplot, and axes3d modules into our program.
Next, we create a figure, add a single subplot, and set the projection to 3d.
Set the z limits to be -1 and +1.
Create 30 data points evenly distributed between -1 and +1 for X and for Y.
Update X and Y using their meshgrid values.
Initialize the wire frame to be None.
We will rotate 360 degrees circling around the original point.
Therefore, we will have 360 picture frames.
For each picture frame, we remove the old wireframe lines before drawing new ones.
Then, we recalculate Z using this formula.
Although complex, they are still element-wise operations.
And phi is the looping index, it changes in each picture frame.
As a result, Z will change in each frame.
Next, we draw the new wireframe using X, Y, and the new Z.
The view_init function will change our view point, or azimuth, so we feel like the wire
frame is rotating.
We pause for 0.05 seconds between each picture frame.
Let's run this animation_3d.py file in a command window.
In the command window, I first change directory to this folder where I store the Python file.
Then I type in python animation_3d.py, I can see the animation now.
It stops after it has rotated 360 degrees.
It seems like water waves or a stingray.
The last one is a real world example.
It plots the hourly electric load data for each day of the entire year of 2012 in California.
This program created a figure used in one of my publications titled Critical peak electricity
pricing for sustainable manufacturing: Modeling and case studies.
You can download the paper here and give it a read if you like.
I'll share the source code caiso_load.py and the dataset caiso_load_2012.csv.
But I will not explain it in this video.
I did provide some comments in the code to help you understand it.
I'll leave it to you to practice and figure out how it works.
It does involve some new stuff we didn't cover in this course.
So, you may need to do some googling to understand some part of the code.
Okay, I just talked about some MatPlotLib gallery examples in this video.
The course materials are available on YouTube and GitHub.
You can watch the course videos in sequence.
If you like this video, please subscribe and share.
I'm Yong Wang.
Thanks for watching.