SlideShare a Scribd company logo
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 1/43
Matplotlib
Assistant Professor :
Dr. Fadaeieslam
By :
Amir Shokri
Farshad Asgharzade
Alireza Gholamnia
Introduction:
Matplotlib is one of the most popular Python packages used for
data visualization. Matplotlib was originally written by John D.
Hunter in 2003. Pyplot is a Matplotlib module which provides a
MATLAB-like interface. Matplotlib is designed to be as usable as
MATLAB, with the ability to use Python, and the advantage of
being free and open-source. Matplotlib is open source and we
can use it freely. The purpose of a plotting package is to assist
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 2/43
you in visualizing your data as easily as possible, with all the
necessary control that is, by using relatively high-level commands
most of the time, and still have the ability to use the low-level
commands when needed.
Installation of Matplotlib:
If you have Python and PIP already installed on a system, then
installation of Matplotlib is very easy. Install it using this
command:
pip install matplotlib
Matplotlib requires the following dependencies:
NumPy
setuptools
cycler
dateutil
kiwisolver
Pillow
pyparsing
Anaconda distribution:
Anaconda is a free and open source distribution of the Python and
R programming languages for large-scale data processing,
predictive analytics, and scientific computing. The distribution
makes package management and deployment simple and easy.
Matplotlib and lots of other useful (data) science tools form part of
the distribution. Package versions are managed by the package
management system Conda. The advantage of Anaconda is that
you have access to over 720 packages that can easily be installed
with Anaconda's Conda, a package, dependency, and
environment manager.
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 3/43
Checking Matplotlib Version:
Once Matplotlib is installed, import it in your applications by
adding the import module statement:
In [1]:
Most of the Matplotlib utilities lies under the pyplot submodule,
and are usually imported under the plt alias:
In [2]:
matplotlib.pyplot is a collection of functions that make matplotlib
work like MATLAB. Each pyplot function makes some change to a
figure: e.g., creates a figure, creates a plotting area in a figure,
plots some lines in a plotting area, decorates the plot with labels,
etc.
Generating visualizations with pyplot
is very quick:
Out[1]: '3.3.2'
import matplotlib
matplotlib.__version__
import matplotlib.pyplot as plt
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 4/43
In [3]:
In [4]:
You may be wondering why the x-axis ranges from 0-3 and the y-
axis from 1-4. If you provide a single list or array to plot, matplotlib
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4],[1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show()
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show()
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 5/43
assumes it is a sequence of y values, and automatically generates
the x values for you. Since python ranges start with 0, the default
x vector has the same length as y but starts with 0. Hence the x
data are [0, 1, 2, 3].
Formatting the style of your plot:
For every x, y pair of arguments, there is an optional third
argument which is the format string that indicates the color and
line type of the plot. The letters and symbols of the format string
are from MATLAB, and you concatenate a color string with a line
style string. The default format string is 'b-', which is a solid blue
line. For example, to plot the above with red circles, you would
issue
In [5]: plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro')
plt.axis([0, 6, 0, 20])
plt.show()
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 6/43
In [6]:
In [7]:
plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'r+') # ditto, but with red pluss
plt.axis([0, 6, 0, 20])
plt.show()
plt.plot([1, 2, 3, 4], [1, 4, 9, 16],'go--', linewidth=2, markersize=12)
plt.axis([0, 6, 0, 20])
plt.show()
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 7/43
In [8]:
Marker Size : You can use the keyword argument markersize or
the shorter version, ms to set the size of the markers
In [9]:
Marker Color: You can use the keyword argument markerfacecolor
or the shorter mfc to set the color inside the edge of the markers:
ypoints = [3, 8, 1, 10]
plt.plot(ypoints, 'o:r')
plt.show()
ypoints = [3, 8, 1, 10]
plt.plot(ypoints, marker = 'o', ms = 20)
plt.show()
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 8/43
In [10]:
For more visit
https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot
(https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot)
Use with numpy
If matplotlib were limited to working with lists, it would be fairly
useless for numeric processing. Generally, you will use numpy
arrays. In fact, all sequences are converted to numpy arrays
internally. The example below illustrates plotting several lines with
different format styles in one function call using arrays.
ypoints =[3, 8, 1, 10]
plt.plot(ypoints, marker = 'o', ms = 20, mec = 'r', mfc = 'r')
plt.show()
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 9/43
In [11]:
Display Multiple Plots
the subplots() function takes three arguments that describes the
layout of the figure. The layout is organized in rows and columns,
which are represented by the first and second argument. The third
argument represents the index of the current plot.
import numpy as np
import matplotlib.pyplot as plt
# evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)
# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t*2, 'bs', t, t*3, 'g^')
plt.show()
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 10/43
In [12]: x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(2, 1, 1)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(2, 1, 2)
plt.plot(x,y)
plt.show()
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 11/43
In [13]: x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(2, 3, 1)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(2, 3, 2)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(2, 3, 3)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(2, 3, 4)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(2, 3, 5)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(2, 3, 6)
plt.plot(x,y)
plt.show()
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 12/43
In [14]:
Subplot2grid() Function
This function gives more flexibility in creating an axes object at a
specific location of the grid. It also allows the axes object to be
spanned across multiple rows or columns.
Plt.subplot2grid(shape, location, rowspan,
colspan)
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(1, 2, 1)
plt.plot(x,y)
plt.title("SALES")
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(1, 2, 2)
plt.plot(x,y)
plt.title("INCOME")
plt.suptitle("MY SHOP")
plt.show()
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 13/43
In [15]:
Grids
The grid() function of axes object sets visibility of grid inside the
figure to on or off. You can also display major / minor (or both)
ticks of the grid. Additionally color, linestyle and linewidth
properties can be set in the grid() function.
a1 = plt.subplot2grid((3,3),(0,0),colspan = 2)
a2 = plt.subplot2grid((3,3),(0,2), rowspan = 3)
a3 = plt.subplot2grid((3,3),(1,0),rowspan = 2, colspan = 2)
x = np.arange(1,10)
a2.plot(x, x*x)
a2.set_title('square')
a1.plot(x, np.exp(x))
a1.set_title('exp')
a3.plot(x, np.log(x))
a3.set_title('log')
plt.tight_layout()
plt.show()
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 14/43
In [16]:
Working with text
text can be used to add text in an arbitrary location, and xlabel,
ylabel and title are used to add text in the indicated locations (see
Text in Matplotlib Plots for a more detailed example)
Using mathematical expressions in text:
plt.text(60, .025, r'$mu=100, sigma=15$')
matplotlib accepts laTeX equation expressions in any text
expression.
import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(1,3, figsize = (12,4))
x = np.arange(1,11)
axes[0].plot(x, x**3, 'g',lw=2)
axes[0].grid(True)
axes[0].set_title('default grid')
axes[1].plot(x, np.exp(x), 'r')
axes[1].grid(color='b', ls = '-.', lw = 0.25)
axes[1].set_title('custom grid')
axes[2].plot(x,x)
axes[2].set_title('no grid')
fig.tight_layout()
plt.show()
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 15/43
In [17]:
Annotating text
The uses of the basic text function above place text at an arbitrary
position on the Axes. A common use for text is to annotate some
feature of the plot, and the annotate method provides helper
functionality to make annotations easy. In an annotation, there are
two points to consider: the location being annotated represented
by the argument xy and the location of the text xytext. Both of
these arguments are (x, y) tuples.
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
# the histogram of the data
n, bins, patches = plt.hist(x, 50, density=1, facecolor='g', alpha=0.75)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$mu=100, sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 16/43
In [18]:
Logarithmic and other nonlinear
axes
matplotlib.pyplot supports not only linear axis scales, but also
logarithmic and logit scales. This is commonly used if data spans
many orders of magnitude. Changing the scale of an axis is easy:
plt.xscale('log')
ax = plt.subplot(111)
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)
plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
arrowprops=dict(facecolor='black', shrink=0.05),
)
plt.ylim(-2, 2)
plt.show()
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 17/43
In [19]:
from matplotlib.pyplot import figure
# make up some data in the open interval (0, 1)
y = np.random.normal(loc=0.5, scale=0.4, size=1000)
y = y[(y > 0) & (y < 1)]
y.sort()
x = np.arange(len(y))
figure(num=None, figsize=(10, 10))
# linear
plt.plot(x, y)
plt.yscale('linear')
plt.title('linear')
plt.grid(True)
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 18/43
In [20]: # log
figure(num=None, figsize=(10, 10))
plt.plot(x, y)
plt.yscale('log')
plt.title('log')
plt.grid(True)
plt.show()
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 19/43
In [21]: # symmetric log
figure(num=None, figsize=(10, 10))
plt.plot(x, y - y.mean())
plt.yscale('symlog', linthresh=0.01)
plt.title('symlog')
plt.grid(True)
plt.show()
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 20/43
In [22]: # logit
figure(num=None, figsize=(10, 30))
plt.plot(x, y)
plt.yscale('logit')
plt.title('logit')
plt.grid(True)
plt.show()
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 21/43
Matplotlib Bars
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 22/43
With Pyplot, you can use the bar() function to draw bar graphs
The bar() function takes arguments that describes the layout of the
bars. The categories and their values represented by the first and
second argument as arrays.
x = ["APPLES", "BANANAS"]
y = [400, 350]plt.bar(x, y)
plt.bar(x, y)
In [23]:
Matplotlib Pie Charts
A Pie Chart can only display one series of data. Pie charts show
the size of items (called wedge) in one data series, proportional to
the sum of the items. The data points in a pie chart are shown as
a percentage of the whole pie. Explode: Maybe you want one of
the wedges to stand out? The explode parameter allows you to
do that. The explode parameter, if specified, and not None, must
be an array with one value for each wedge.
x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])
plt.bar(x, y, width = 0.5)
plt.show()
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 23/43
In [24]:
Explode: Maybe you want one of the wedges to stand out? The
explode parameter allows you to do that. The explode parameter,
if specified, and not None, must be an array with one value for
each wedge.
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.axis('equal')
langs = ['C', 'C++', 'Java', 'Python', 'PHP']
students = [23,17,35,29,12]
ax.pie(students, labels = langs,autopct='%1.2f%%')
plt.show()
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 24/43
In [25]:
3D Surface plot
Surface plot shows a functional relationship between a designated
dependent variable (Y), and two independent variables (X and Z).
The plot is a companion plot to the contour plot. A surface plot is
like a wireframe plot, but each face of the wireframe is a filled
polygon. This can aid perception of the topology of the surface
being visualized. The plot_surface() function x,y and z as
arguments.
y = np.array([35, 25, 25, 15])
mylabels = ["C", "C++", "Python", "Java"]
myexplode = [0.2, 0, 0, 0]
plt.pie(y, explode = myexplode , labels = mylabels)
plt.show()
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 25/43
In [26]: from mpl_toolkits import mplot3d
x = np.outer(np.linspace(-2, 2, 30), np.ones(30))
y = x.copy().T
z = np.cos(x ** 2 + y ** 2)
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.plot_surface(x, y, z,cmap='viridis', edgecolor='none')
ax.set_title('Surface plot')
plt.show()
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 26/43
In [27]:
from mpl_toolkits.mplot3d import Axes3D
from scipy.stats import multivariate_normal
x, y = np.mgrid[-1.0:1.0:30j, -1.0:1.0:30j]
xy = np.column_stack([x.flat, y.flat])
mu = np.array([0.0, 0.0])
sigma = np.array([.5, .5])
covariance = np.diag(sigma**2)
z = multivariate_normal.pdf(xy, mean=mu, cov=covariance)
z = z.reshape(x.shape)
fig = plt.figure(num=None, figsize=(10, 10))
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(x,y,z)
plt.show()
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 27/43
Seaborn
Seaborn is a Python data visualization library based on matplotlib.
It provides a high-level interface for drawing attractive and
informative statistical graphics.
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 28/43
In [28]:
Out[28]: <seaborn.axisgrid.PairGrid at 0x7f94b6a11dd0>
import seaborn as sns
df = sns.load_dataset("penguins")
sns.pairplot(df, hue="species")
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 29/43
In [29]:
Working with Images
The image module in Matplotlib package provides functionalities
required for loading, rescaling and displaying image. Loading
image data is supported by the Pillow library and Matplotlib relies
on the Pillow library to load image data. The imread() function is
used to read image data in an ndarray object of float32 dtype.
tips = sns.load_dataset("tips")
g = sns.jointplot(x="total_bill", y="tip", data=tips,
kind="reg", truncate=False,
xlim=(0, 60), ylim=(0, 12),
color="m", height=7)
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 30/43
In [30]:
In [31]:
Get image size (width, height,
dimension)
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from matplotlib.pyplot import figure
img = mpimg.imread('mpl.png')
figure(num=None, figsize=(10, 10))
imgplot = plt.imshow(img)
plt.imsave("logo.png", img, origin = 'lower')
newimg = mpimg.imread('logo.png')
imgplot = plt.imshow(newimg)
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 31/43
In [32]:
(512, 512, 3)
img_lena = mpimg.imread('lena.png')
print(img_lena.shape)
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 32/43
In [33]:
figure(num=None, figsize=(15, 10))
plt.subplot(2, 2, 1)
plt.axis('off')
plt.imshow(img_lena[:,:,:])
plt.title("Orginal image")
plt.subplot(2, 2, 2)
plt.axis('off')
red_img_lena = img_lena[:,:,0]
plt.imshow(red_img_lena)
plt.title("Red Chanel")
plt.subplot(2, 2, 3)
plt.axis('off')
green_img_lena = img_lena[:,:,1]
plt.imshow(green_img_lena)
plt.title("Green Chanel")
plt.subplot(2, 2, 4)
plt.axis('off')
blue_img_lena = img_lena[:,:,2]
plt.imshow(blue_img_lena)
plt.title("Blue Chanel")
plt.suptitle(" images")
plt.show()
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 33/43
Examining a specific data range
Sometimes you want to enhance the contrast in your image, or
expand the contrast in a particular region while sacrificing the
detail in colors that don't vary much, or don't matter. A good tool
to find interesting regions is the histogram. To create a histogram
of our image data, we use the hist() function.
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 34/43
In [34]:
figure(num=None, figsize=(15, 10))
plt.subplot(2, 2, 1)
plt.hist(img_lena.ravel(), bins=256, range=(0.0, 1.0),color = 'Black')
plt.title("lena image histogram")
plt.subplot(2, 2, 2)
plt.hist(red_img_lena.ravel(), bins=256, range=(0.0, 1.0), color = 'red')
plt.title("red chanel of lena image histogram")
plt.subplot(2, 2, 3)
plt.hist(green_img_lena.ravel(), bins=256, range=(0.0, 1.0),color = 'Green'
plt.title("green chanel of lena image histogram")
plt.subplot(2, 2, 4)
plt.hist(blue_img_lena.ravel(), bins=256, range=(0.0, 1.0), color = 'Blue')
plt.title("blue chanel of lena image histogram")
plt.suptitle(" images histogram")
plt.show()
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 35/43
In color images, we have 3 color channels representing RGB. In
Combined Color Histogram the intensity count is the sum of all
three color channels.
In [35]:
Histogram equalization
Histogram equalization is a method in image processing of
contrast adjustment using the image's histogram.
import matplotlib.pyplot as plt
image = plt.imread('lena.png')
_ = plt.hist(image.ravel(), bins = 256, color = 'orange', )
_ = plt.hist(image[:, :, 0].ravel(), bins = 256, color = 'red', alpha = 0.5
_ = plt.hist(image[:, :, 1].ravel(), bins = 256, color = 'Green', alpha = 0
_ = plt.hist(image[:, :, 2].ravel(), bins = 256, color = 'Blue', alpha = 0.
_ = plt.xlabel('Intensity Value')
_ = plt.ylabel('Count')
_ = plt.legend(['Total', 'Red_Channel', 'Green_Channel', 'Blue_Channel'])
plt.show()
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 36/43
In [40]: # Importing Image and ImageOps module from PIL package
from PIL import Image, ImageOps
figure(num=None, figsize=(15, 10))
im1 = Image.open(r"lena.png")
im2 = ImageOps.equalize(im1, mask = None)
plt.axis('off')
plt.imshow(im2)
plt.show()
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 37/43
In [41]:
Out[41]: Text(0.5, 1.0, 'after histogram eq ')
import cv2
import numpy as np
from matplotlib import pyplot as plt
figure(num=None, figsize=(15, 10))
img_cv = cv2.imread('lena.png',0)
equ_cv = cv2.equalizeHist(img_cv)
plt.subplot(2, 2, 1)
plt.axis('off')
plt.imshow(img_cv)
plt.subplot(2, 2, 2)
plt.axis('off')
plt.imshow(equ_cv)
plt.subplot(2, 2, 3)
plt.hist(img_cv.ravel(),256,[0,256]);
plt.title("lena image histogram")
plt.subplot(2, 2, 4)
plt.hist(equ_cv.ravel(),256,[0,256]);
plt.title("after histogram eq ")
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 38/43
scikit-image
scikit-image is a collection of algorithms for image processing.
In [43]:
NumPy
Sometimes you want to enhance the contrast in your image, or
expand the contrast in a particular region while sacrificing the
detail in colors that don't vary much, or don't matter. A good tool
to find interesting regions is the histogram. To create a histogram
of our image data, we use the hist() function.
Out[43]: <matplotlib.image.AxesImage at 0x7f949f255b50>
from skimage import data,filters
figure(num=None, figsize=(15, 10))
img_coin = data.coins()
edges_coin = filters.sobel(img_coin)
plt.subplot(1, 2, 1)
plt.axis('off')
plt.imshow(img_coin, cmap='gray')
plt.subplot(1, 2, 2)
plt.axis('off')
plt.imshow(edges_coin, cmap='gray')
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 39/43
In [44]:
Using SciPy for blurring using a
Gaussian filter:
Out[44]: <matplotlib.image.AxesImage at 0x7f949fbaab50>
figure(num=None, figsize=(15, 10))
image_camera = data.camera()
plt.subplot(1, 2, 1)
plt.axis('off')
plt.imshow(image_camera, cmap='gray')
mask_camera = image_camera < 87
image_camera[mask_camera]=255
plt.subplot(1, 2, 2)
plt.axis('off')
plt.imshow(image_camera, cmap='gray')
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 40/43
In [45]:
exciting small project
Out[45]: <matplotlib.image.AxesImage at 0x7f94a010fdd0>
from scipy import misc,ndimage
figure(num=None, figsize=(15, 10))
ime_face = misc.face()
blurred_face = ndimage.gaussian_filter(ime_face, sigma=3)
very_blurred = ndimage.gaussian_filter(ime_face, sigma=5)
plt.subplot(1, 3, 1)
plt.axis('off')
plt.imshow(ime_face)
plt.subplot(1, 3, 2)
plt.axis('off')
plt.imshow(blurred_face)
plt.subplot(1, 3, 3)
plt.axis('off')
plt.imshow(very_blurred)
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 41/43
In [46]:
Out[46]: <matplotlib.legend.Legend at 0x7f949fab9450>
import pandas as pd
import datetime
import pandas_datareader.data as web
from pandas import Series, DataFrame
figure(num=None, figsize=(15, 10))
start = datetime.datetime(2010, 1, 1)
end = datetime.datetime(2017, 1, 11)
df = web.DataReader("AAPL", 'yahoo', start, end)
close_px = df['Adj Close']
mavg = close_px.rolling(window=100).mean()
from matplotlib import style
# Adjusting the size of matplotlib
import matplotlib as mpl
mpl.rc('figure', figsize=(8, 7))
mpl.__version__
# Adjusting the style of matplotlib
style.use('ggplot')
close_px.plot(label='AAPL')
mavg.plot(label='mavg')
plt.legend()
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 42/43
real data project
11/8/2020 matplotlib - Jupyter Notebook
localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 43/43
In [1]:
MovieWriter imagemagick unavailable; using Pillow instead.
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
plt.style.use('seaborn-pastel')
fig = plt.figure()
ax = plt.axes(xlim=(0, 4), ylim=(-2, 2))
line, = ax.plot([], [], lw=3)
def init():
line.set_data([], [])
return line,
def animate(i):
x = np.linspace(0, 4, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i))
line.set_data(x, y)
return line,
anim = FuncAnimation(fig, animate, init_func=init,
frames=200, interval=20, blit=True)
anim.save('sine_wave.gif', writer='imagemagick')

More Related Content

What's hot

Introduction to pandas
Introduction to pandasIntroduction to pandas
Introduction to pandas
Piyush rai
 
Python - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning LibrariesPython - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning Libraries
Andrew Ferlitsch
 
MatplotLib.pptx
MatplotLib.pptxMatplotLib.pptx
MatplotLib.pptx
Paras Intotech
 
Python Pandas
Python PandasPython Pandas
Python Pandas
Sunil OS
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
TMARAGATHAM
 
Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
Emertxe Information Technologies Pvt Ltd
 
Data visualization in Python
Data visualization in PythonData visualization in Python
Data visualization in Python
Marc Garcia
 
Numpy tutorial
Numpy tutorialNumpy tutorial
Numpy tutorial
HarikaReddy115
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
Devashish Kumar
 
Python programming
Python  programmingPython  programming
Python programming
Ashwin Kumar Ramasamy
 
Python NumPy Tutorial | NumPy Array | Edureka
Python NumPy Tutorial | NumPy Array | EdurekaPython NumPy Tutorial | NumPy Array | Edureka
Python NumPy Tutorial | NumPy Array | Edureka
Edureka!
 
Date and Time Module in Python | Edureka
Date and Time Module in Python | EdurekaDate and Time Module in Python | Edureka
Date and Time Module in Python | Edureka
Edureka!
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
narmadhakin
 
NumPy
NumPyNumPy
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
hydpy
 
PYTHON-Chapter 4-Plotting and Data Science PyLab - MAULIK BORSANIYA
PYTHON-Chapter 4-Plotting and Data Science  PyLab - MAULIK BORSANIYAPYTHON-Chapter 4-Plotting and Data Science  PyLab - MAULIK BORSANIYA
PYTHON-Chapter 4-Plotting and Data Science PyLab - MAULIK BORSANIYA
Maulik Borsaniya
 
String Manipulation in Python
String Manipulation in PythonString Manipulation in Python
String Manipulation in Python
Pooja B S
 
Arrays and structures
Arrays and structuresArrays and structures
Arrays and structuresMohd Arif
 
Tuples in Python
Tuples in PythonTuples in Python
Tuples in Python
DPS Ranipur Haridwar UK
 
Data Analysis in Python-NumPy
Data Analysis in Python-NumPyData Analysis in Python-NumPy
Data Analysis in Python-NumPy
Devashish Kumar
 

What's hot (20)

Introduction to pandas
Introduction to pandasIntroduction to pandas
Introduction to pandas
 
Python - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning LibrariesPython - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning Libraries
 
MatplotLib.pptx
MatplotLib.pptxMatplotLib.pptx
MatplotLib.pptx
 
Python Pandas
Python PandasPython Pandas
Python Pandas
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 
Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
 
Data visualization in Python
Data visualization in PythonData visualization in Python
Data visualization in Python
 
Numpy tutorial
Numpy tutorialNumpy tutorial
Numpy tutorial
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
Python programming
Python  programmingPython  programming
Python programming
 
Python NumPy Tutorial | NumPy Array | Edureka
Python NumPy Tutorial | NumPy Array | EdurekaPython NumPy Tutorial | NumPy Array | Edureka
Python NumPy Tutorial | NumPy Array | Edureka
 
Date and Time Module in Python | Edureka
Date and Time Module in Python | EdurekaDate and Time Module in Python | Edureka
Date and Time Module in Python | Edureka
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
 
NumPy
NumPyNumPy
NumPy
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
PYTHON-Chapter 4-Plotting and Data Science PyLab - MAULIK BORSANIYA
PYTHON-Chapter 4-Plotting and Data Science  PyLab - MAULIK BORSANIYAPYTHON-Chapter 4-Plotting and Data Science  PyLab - MAULIK BORSANIYA
PYTHON-Chapter 4-Plotting and Data Science PyLab - MAULIK BORSANIYA
 
String Manipulation in Python
String Manipulation in PythonString Manipulation in Python
String Manipulation in Python
 
Arrays and structures
Arrays and structuresArrays and structures
Arrays and structures
 
Tuples in Python
Tuples in PythonTuples in Python
Tuples in Python
 
Data Analysis in Python-NumPy
Data Analysis in Python-NumPyData Analysis in Python-NumPy
Data Analysis in Python-NumPy
 

Similar to Matplotlib

Introduction to Pylab and Matploitlib.
Introduction to Pylab and Matploitlib. Introduction to Pylab and Matploitlib.
Introduction to Pylab and Matploitlib.
yazad dumasia
 
matplotlib-installatin-interactive-contour-example-guide
matplotlib-installatin-interactive-contour-example-guidematplotlib-installatin-interactive-contour-example-guide
matplotlib-installatin-interactive-contour-example-guideArulalan T
 
UNit-III. part 2.pdf
UNit-III. part 2.pdfUNit-III. part 2.pdf
UNit-III. part 2.pdf
MastiCreation
 
Python for Machine Learning(MatPlotLib).pptx
Python for Machine Learning(MatPlotLib).pptxPython for Machine Learning(MatPlotLib).pptx
Python for Machine Learning(MatPlotLib).pptx
Dr. Amanpreet Kaur
 
Mmc manual
Mmc manualMmc manual
Mmc manual
Urvi Surat
 
Data Visualization 2020_21
Data Visualization 2020_21Data Visualization 2020_21
Data Visualization 2020_21
Sangita Panchal
 
12-IP.pdf
12-IP.pdf12-IP.pdf
12-IP.pdf
kajalkhorwal106
 
Seeing Like Software
Seeing Like SoftwareSeeing Like Software
Seeing Like Software
Andrew Lovett-Barron
 
Simplifying Matplotlib by examples
Simplifying Matplotlib by examplesSimplifying Matplotlib by examples
Simplifying Matplotlib by examples
Mohammed Ali İsmail
 
Python for Scientific Computing -- Ricardo Cruz
Python for Scientific Computing -- Ricardo CruzPython for Scientific Computing -- Ricardo Cruz
Python for Scientific Computing -- Ricardo Cruz
rpmcruz
 
16. Data VIsualization using PyPlot.pdf
16. Data VIsualization using PyPlot.pdf16. Data VIsualization using PyPlot.pdf
16. Data VIsualization using PyPlot.pdf
RrCreations5
 
Matlab Nn Intro
Matlab Nn IntroMatlab Nn Intro
Matlab Nn Intro
Imthias Ahamed
 
Project gnuplot
Project gnuplotProject gnuplot
Project gnuplot
Sabyasachi Ray
 
PPT on Data Science Using Python
PPT on Data Science Using PythonPPT on Data Science Using Python
PPT on Data Science Using Python
NishantKumar1179
 
maXbox starter68 machine learning VI
maXbox starter68 machine learning VImaXbox starter68 machine learning VI
maXbox starter68 machine learning VI
Max Kleiner
 
Learn basics of Clojure/script and Reagent
Learn basics of Clojure/script and ReagentLearn basics of Clojure/script and Reagent
Learn basics of Clojure/script and Reagent
Maty Fedak
 
Use the Matplotlib, Luke @ PyCon Taiwan 2012
Use the Matplotlib, Luke @ PyCon Taiwan 2012Use the Matplotlib, Luke @ PyCon Taiwan 2012
Use the Matplotlib, Luke @ PyCon Taiwan 2012
Wen-Wei Liao
 
Dsp file
Dsp fileDsp file
Python for Data Science
Python for Data SciencePython for Data Science
Python for Data Science
Panimalar Engineering College
 
Kevin merchantss
Kevin merchantssKevin merchantss
Kevin merchantss
dharmesh69
 

Similar to Matplotlib (20)

Introduction to Pylab and Matploitlib.
Introduction to Pylab and Matploitlib. Introduction to Pylab and Matploitlib.
Introduction to Pylab and Matploitlib.
 
matplotlib-installatin-interactive-contour-example-guide
matplotlib-installatin-interactive-contour-example-guidematplotlib-installatin-interactive-contour-example-guide
matplotlib-installatin-interactive-contour-example-guide
 
UNit-III. part 2.pdf
UNit-III. part 2.pdfUNit-III. part 2.pdf
UNit-III. part 2.pdf
 
Python for Machine Learning(MatPlotLib).pptx
Python for Machine Learning(MatPlotLib).pptxPython for Machine Learning(MatPlotLib).pptx
Python for Machine Learning(MatPlotLib).pptx
 
Mmc manual
Mmc manualMmc manual
Mmc manual
 
Data Visualization 2020_21
Data Visualization 2020_21Data Visualization 2020_21
Data Visualization 2020_21
 
12-IP.pdf
12-IP.pdf12-IP.pdf
12-IP.pdf
 
Seeing Like Software
Seeing Like SoftwareSeeing Like Software
Seeing Like Software
 
Simplifying Matplotlib by examples
Simplifying Matplotlib by examplesSimplifying Matplotlib by examples
Simplifying Matplotlib by examples
 
Python for Scientific Computing -- Ricardo Cruz
Python for Scientific Computing -- Ricardo CruzPython for Scientific Computing -- Ricardo Cruz
Python for Scientific Computing -- Ricardo Cruz
 
16. Data VIsualization using PyPlot.pdf
16. Data VIsualization using PyPlot.pdf16. Data VIsualization using PyPlot.pdf
16. Data VIsualization using PyPlot.pdf
 
Matlab Nn Intro
Matlab Nn IntroMatlab Nn Intro
Matlab Nn Intro
 
Project gnuplot
Project gnuplotProject gnuplot
Project gnuplot
 
PPT on Data Science Using Python
PPT on Data Science Using PythonPPT on Data Science Using Python
PPT on Data Science Using Python
 
maXbox starter68 machine learning VI
maXbox starter68 machine learning VImaXbox starter68 machine learning VI
maXbox starter68 machine learning VI
 
Learn basics of Clojure/script and Reagent
Learn basics of Clojure/script and ReagentLearn basics of Clojure/script and Reagent
Learn basics of Clojure/script and Reagent
 
Use the Matplotlib, Luke @ PyCon Taiwan 2012
Use the Matplotlib, Luke @ PyCon Taiwan 2012Use the Matplotlib, Luke @ PyCon Taiwan 2012
Use the Matplotlib, Luke @ PyCon Taiwan 2012
 
Dsp file
Dsp fileDsp file
Dsp file
 
Python for Data Science
Python for Data SciencePython for Data Science
Python for Data Science
 
Kevin merchantss
Kevin merchantssKevin merchantss
Kevin merchantss
 

More from Amir Shokri

LAUNCH - growth practices - PRODUCT MANAGER
LAUNCH - growth practices - PRODUCT MANAGERLAUNCH - growth practices - PRODUCT MANAGER
LAUNCH - growth practices - PRODUCT MANAGER
Amir Shokri
 
Remote work
Remote workRemote work
Remote work
Amir Shokri
 
Project Management Growth Practices
Project Management Growth PracticesProject Management Growth Practices
Project Management Growth Practices
Amir Shokri
 
GROWTH PRACTICES - Cracking the PM Career - CHAPTER 7
GROWTH PRACTICES - Cracking the PM Career - CHAPTER 7GROWTH PRACTICES - Cracking the PM Career - CHAPTER 7
GROWTH PRACTICES - Cracking the PM Career - CHAPTER 7
Amir Shokri
 
Numbers, math operation, converting bases
Numbers, math operation, converting basesNumbers, math operation, converting bases
Numbers, math operation, converting bases
Amir Shokri
 
GROWTH PRACTICES - Cracking the PM Career - CHAPTER 4
GROWTH PRACTICES - Cracking the PM Career - CHAPTER 4GROWTH PRACTICES - Cracking the PM Career - CHAPTER 4
GROWTH PRACTICES - Cracking the PM Career - CHAPTER 4
Amir Shokri
 
review of image memorability methods
review of image memorability methodsreview of image memorability methods
review of image memorability methods
Amir Shokri
 
key.net
key.netkey.net
key.net
Amir Shokri
 
beyesian learning exercises
beyesian learning exercisesbeyesian learning exercises
beyesian learning exercises
Amir Shokri
 
Bayesian learning
Bayesian learningBayesian learning
Bayesian learning
Amir Shokri
 
machine learning code
machine learning codemachine learning code
machine learning code
Amir Shokri
 
machine learning - id3, find-s, candidate elimination, desicion tree example
machine learning - id3, find-s, candidate elimination, desicion tree examplemachine learning - id3, find-s, candidate elimination, desicion tree example
machine learning - id3, find-s, candidate elimination, desicion tree example
Amir Shokri
 
ID3 Algorithm
ID3 AlgorithmID3 Algorithm
ID3 Algorithm
Amir Shokri
 
Concept learning
Concept learningConcept learning
Concept learning
Amir Shokri
 
logical operators decision tree
logical operators decision treelogical operators decision tree
logical operators decision tree
Amir Shokri
 
Mining social network graphs - persian
Mining social network graphs - persianMining social network graphs - persian
Mining social network graphs - persian
Amir Shokri
 
product glossary
product glossaryproduct glossary
product glossary
Amir Shokri
 
Popular Maple codes Book - Persian
Popular Maple codes Book - PersianPopular Maple codes Book - Persian
Popular Maple codes Book - Persian
Amir Shokri
 
deepswarm optimising convolutional neural networks using swarm intelligence (...
deepswarm optimising convolutional neural networks using swarm intelligence (...deepswarm optimising convolutional neural networks using swarm intelligence (...
deepswarm optimising convolutional neural networks using swarm intelligence (...
Amir Shokri
 

More from Amir Shokri (20)

LAUNCH - growth practices - PRODUCT MANAGER
LAUNCH - growth practices - PRODUCT MANAGERLAUNCH - growth practices - PRODUCT MANAGER
LAUNCH - growth practices - PRODUCT MANAGER
 
Remote work
Remote workRemote work
Remote work
 
Project Management Growth Practices
Project Management Growth PracticesProject Management Growth Practices
Project Management Growth Practices
 
GROWTH PRACTICES - Cracking the PM Career - CHAPTER 7
GROWTH PRACTICES - Cracking the PM Career - CHAPTER 7GROWTH PRACTICES - Cracking the PM Career - CHAPTER 7
GROWTH PRACTICES - Cracking the PM Career - CHAPTER 7
 
Numbers, math operation, converting bases
Numbers, math operation, converting basesNumbers, math operation, converting bases
Numbers, math operation, converting bases
 
GROWTH PRACTICES - Cracking the PM Career - CHAPTER 4
GROWTH PRACTICES - Cracking the PM Career - CHAPTER 4GROWTH PRACTICES - Cracking the PM Career - CHAPTER 4
GROWTH PRACTICES - Cracking the PM Career - CHAPTER 4
 
review of image memorability methods
review of image memorability methodsreview of image memorability methods
review of image memorability methods
 
key.net
key.netkey.net
key.net
 
beyesian learning exercises
beyesian learning exercisesbeyesian learning exercises
beyesian learning exercises
 
Knn
KnnKnn
Knn
 
Bayesian learning
Bayesian learningBayesian learning
Bayesian learning
 
machine learning code
machine learning codemachine learning code
machine learning code
 
machine learning - id3, find-s, candidate elimination, desicion tree example
machine learning - id3, find-s, candidate elimination, desicion tree examplemachine learning - id3, find-s, candidate elimination, desicion tree example
machine learning - id3, find-s, candidate elimination, desicion tree example
 
ID3 Algorithm
ID3 AlgorithmID3 Algorithm
ID3 Algorithm
 
Concept learning
Concept learningConcept learning
Concept learning
 
logical operators decision tree
logical operators decision treelogical operators decision tree
logical operators decision tree
 
Mining social network graphs - persian
Mining social network graphs - persianMining social network graphs - persian
Mining social network graphs - persian
 
product glossary
product glossaryproduct glossary
product glossary
 
Popular Maple codes Book - Persian
Popular Maple codes Book - PersianPopular Maple codes Book - Persian
Popular Maple codes Book - Persian
 
deepswarm optimising convolutional neural networks using swarm intelligence (...
deepswarm optimising convolutional neural networks using swarm intelligence (...deepswarm optimising convolutional neural networks using swarm intelligence (...
deepswarm optimising convolutional neural networks using swarm intelligence (...
 

Recently uploaded

Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
Peter Caitens
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
MayankTawar1
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
Sharepoint Designs
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 

Recently uploaded (20)

Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 

Matplotlib

  • 1. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 1/43 Matplotlib Assistant Professor : Dr. Fadaeieslam By : Amir Shokri Farshad Asgharzade Alireza Gholamnia Introduction: Matplotlib is one of the most popular Python packages used for data visualization. Matplotlib was originally written by John D. Hunter in 2003. Pyplot is a Matplotlib module which provides a MATLAB-like interface. Matplotlib is designed to be as usable as MATLAB, with the ability to use Python, and the advantage of being free and open-source. Matplotlib is open source and we can use it freely. The purpose of a plotting package is to assist
  • 2. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 2/43 you in visualizing your data as easily as possible, with all the necessary control that is, by using relatively high-level commands most of the time, and still have the ability to use the low-level commands when needed. Installation of Matplotlib: If you have Python and PIP already installed on a system, then installation of Matplotlib is very easy. Install it using this command: pip install matplotlib Matplotlib requires the following dependencies: NumPy setuptools cycler dateutil kiwisolver Pillow pyparsing Anaconda distribution: Anaconda is a free and open source distribution of the Python and R programming languages for large-scale data processing, predictive analytics, and scientific computing. The distribution makes package management and deployment simple and easy. Matplotlib and lots of other useful (data) science tools form part of the distribution. Package versions are managed by the package management system Conda. The advantage of Anaconda is that you have access to over 720 packages that can easily be installed with Anaconda's Conda, a package, dependency, and environment manager.
  • 3. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 3/43 Checking Matplotlib Version: Once Matplotlib is installed, import it in your applications by adding the import module statement: In [1]: Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported under the plt alias: In [2]: matplotlib.pyplot is a collection of functions that make matplotlib work like MATLAB. Each pyplot function makes some change to a figure: e.g., creates a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc. Generating visualizations with pyplot is very quick: Out[1]: '3.3.2' import matplotlib matplotlib.__version__ import matplotlib.pyplot as plt
  • 4. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 4/43 In [3]: In [4]: You may be wondering why the x-axis ranges from 0-3 and the y- axis from 1-4. If you provide a single list or array to plot, matplotlib import matplotlib.pyplot as plt plt.plot([1, 2, 3, 4],[1, 2, 3, 4]) plt.ylabel('some numbers') plt.show() plt.plot([1, 2, 3, 4]) plt.ylabel('some numbers') plt.show()
  • 5. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 5/43 assumes it is a sequence of y values, and automatically generates the x values for you. Since python ranges start with 0, the default x vector has the same length as y but starts with 0. Hence the x data are [0, 1, 2, 3]. Formatting the style of your plot: For every x, y pair of arguments, there is an optional third argument which is the format string that indicates the color and line type of the plot. The letters and symbols of the format string are from MATLAB, and you concatenate a color string with a line style string. The default format string is 'b-', which is a solid blue line. For example, to plot the above with red circles, you would issue In [5]: plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro') plt.axis([0, 6, 0, 20]) plt.show()
  • 6. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 6/43 In [6]: In [7]: plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'r+') # ditto, but with red pluss plt.axis([0, 6, 0, 20]) plt.show() plt.plot([1, 2, 3, 4], [1, 4, 9, 16],'go--', linewidth=2, markersize=12) plt.axis([0, 6, 0, 20]) plt.show()
  • 7. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 7/43 In [8]: Marker Size : You can use the keyword argument markersize or the shorter version, ms to set the size of the markers In [9]: Marker Color: You can use the keyword argument markerfacecolor or the shorter mfc to set the color inside the edge of the markers: ypoints = [3, 8, 1, 10] plt.plot(ypoints, 'o:r') plt.show() ypoints = [3, 8, 1, 10] plt.plot(ypoints, marker = 'o', ms = 20) plt.show()
  • 8. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 8/43 In [10]: For more visit https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot (https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot) Use with numpy If matplotlib were limited to working with lists, it would be fairly useless for numeric processing. Generally, you will use numpy arrays. In fact, all sequences are converted to numpy arrays internally. The example below illustrates plotting several lines with different format styles in one function call using arrays. ypoints =[3, 8, 1, 10] plt.plot(ypoints, marker = 'o', ms = 20, mec = 'r', mfc = 'r') plt.show()
  • 9. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 9/43 In [11]: Display Multiple Plots the subplots() function takes three arguments that describes the layout of the figure. The layout is organized in rows and columns, which are represented by the first and second argument. The third argument represents the index of the current plot. import numpy as np import matplotlib.pyplot as plt # evenly sampled time at 200ms intervals t = np.arange(0., 5., 0.2) # red dashes, blue squares and green triangles plt.plot(t, t, 'r--', t, t*2, 'bs', t, t*3, 'g^') plt.show()
  • 10. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 10/43 In [12]: x = np.array([0, 1, 2, 3]) y = np.array([3, 8, 1, 10]) plt.subplot(2, 1, 1) plt.plot(x,y) x = np.array([0, 1, 2, 3]) y = np.array([10, 20, 30, 40]) plt.subplot(2, 1, 2) plt.plot(x,y) plt.show()
  • 11. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 11/43 In [13]: x = np.array([0, 1, 2, 3]) y = np.array([3, 8, 1, 10]) plt.subplot(2, 3, 1) plt.plot(x,y) x = np.array([0, 1, 2, 3]) y = np.array([10, 20, 30, 40]) plt.subplot(2, 3, 2) plt.plot(x,y) x = np.array([0, 1, 2, 3]) y = np.array([3, 8, 1, 10]) plt.subplot(2, 3, 3) plt.plot(x,y) x = np.array([0, 1, 2, 3]) y = np.array([10, 20, 30, 40]) plt.subplot(2, 3, 4) plt.plot(x,y) x = np.array([0, 1, 2, 3]) y = np.array([3, 8, 1, 10]) plt.subplot(2, 3, 5) plt.plot(x,y) x = np.array([0, 1, 2, 3]) y = np.array([10, 20, 30, 40]) plt.subplot(2, 3, 6) plt.plot(x,y) plt.show()
  • 12. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 12/43 In [14]: Subplot2grid() Function This function gives more flexibility in creating an axes object at a specific location of the grid. It also allows the axes object to be spanned across multiple rows or columns. Plt.subplot2grid(shape, location, rowspan, colspan) x = np.array([0, 1, 2, 3]) y = np.array([3, 8, 1, 10]) plt.subplot(1, 2, 1) plt.plot(x,y) plt.title("SALES") x = np.array([0, 1, 2, 3]) y = np.array([10, 20, 30, 40]) plt.subplot(1, 2, 2) plt.plot(x,y) plt.title("INCOME") plt.suptitle("MY SHOP") plt.show()
  • 13. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 13/43 In [15]: Grids The grid() function of axes object sets visibility of grid inside the figure to on or off. You can also display major / minor (or both) ticks of the grid. Additionally color, linestyle and linewidth properties can be set in the grid() function. a1 = plt.subplot2grid((3,3),(0,0),colspan = 2) a2 = plt.subplot2grid((3,3),(0,2), rowspan = 3) a3 = plt.subplot2grid((3,3),(1,0),rowspan = 2, colspan = 2) x = np.arange(1,10) a2.plot(x, x*x) a2.set_title('square') a1.plot(x, np.exp(x)) a1.set_title('exp') a3.plot(x, np.log(x)) a3.set_title('log') plt.tight_layout() plt.show()
  • 14. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 14/43 In [16]: Working with text text can be used to add text in an arbitrary location, and xlabel, ylabel and title are used to add text in the indicated locations (see Text in Matplotlib Plots for a more detailed example) Using mathematical expressions in text: plt.text(60, .025, r'$mu=100, sigma=15$') matplotlib accepts laTeX equation expressions in any text expression. import matplotlib.pyplot as plt import numpy as np fig, axes = plt.subplots(1,3, figsize = (12,4)) x = np.arange(1,11) axes[0].plot(x, x**3, 'g',lw=2) axes[0].grid(True) axes[0].set_title('default grid') axes[1].plot(x, np.exp(x), 'r') axes[1].grid(color='b', ls = '-.', lw = 0.25) axes[1].set_title('custom grid') axes[2].plot(x,x) axes[2].set_title('no grid') fig.tight_layout() plt.show()
  • 15. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 15/43 In [17]: Annotating text The uses of the basic text function above place text at an arbitrary position on the Axes. A common use for text is to annotate some feature of the plot, and the annotate method provides helper functionality to make annotations easy. In an annotation, there are two points to consider: the location being annotated represented by the argument xy and the location of the text xytext. Both of these arguments are (x, y) tuples. mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) # the histogram of the data n, bins, patches = plt.hist(x, 50, density=1, facecolor='g', alpha=0.75) plt.xlabel('Smarts') plt.ylabel('Probability') plt.title('Histogram of IQ') plt.text(60, .025, r'$mu=100, sigma=15$') plt.axis([40, 160, 0, 0.03]) plt.grid(True) plt.show()
  • 16. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 16/43 In [18]: Logarithmic and other nonlinear axes matplotlib.pyplot supports not only linear axis scales, but also logarithmic and logit scales. This is commonly used if data spans many orders of magnitude. Changing the scale of an axis is easy: plt.xscale('log') ax = plt.subplot(111) t = np.arange(0.0, 5.0, 0.01) s = np.cos(2*np.pi*t) line, = plt.plot(t, s, lw=2) plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5), arrowprops=dict(facecolor='black', shrink=0.05), ) plt.ylim(-2, 2) plt.show()
  • 17. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 17/43 In [19]: from matplotlib.pyplot import figure # make up some data in the open interval (0, 1) y = np.random.normal(loc=0.5, scale=0.4, size=1000) y = y[(y > 0) & (y < 1)] y.sort() x = np.arange(len(y)) figure(num=None, figsize=(10, 10)) # linear plt.plot(x, y) plt.yscale('linear') plt.title('linear') plt.grid(True)
  • 18. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 18/43 In [20]: # log figure(num=None, figsize=(10, 10)) plt.plot(x, y) plt.yscale('log') plt.title('log') plt.grid(True) plt.show()
  • 19. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 19/43 In [21]: # symmetric log figure(num=None, figsize=(10, 10)) plt.plot(x, y - y.mean()) plt.yscale('symlog', linthresh=0.01) plt.title('symlog') plt.grid(True) plt.show()
  • 20. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 20/43 In [22]: # logit figure(num=None, figsize=(10, 30)) plt.plot(x, y) plt.yscale('logit') plt.title('logit') plt.grid(True) plt.show()
  • 21. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 21/43 Matplotlib Bars
  • 22. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 22/43 With Pyplot, you can use the bar() function to draw bar graphs The bar() function takes arguments that describes the layout of the bars. The categories and their values represented by the first and second argument as arrays. x = ["APPLES", "BANANAS"] y = [400, 350]plt.bar(x, y) plt.bar(x, y) In [23]: Matplotlib Pie Charts A Pie Chart can only display one series of data. Pie charts show the size of items (called wedge) in one data series, proportional to the sum of the items. The data points in a pie chart are shown as a percentage of the whole pie. Explode: Maybe you want one of the wedges to stand out? The explode parameter allows you to do that. The explode parameter, if specified, and not None, must be an array with one value for each wedge. x = np.array(["A", "B", "C", "D"]) y = np.array([3, 8, 1, 10]) plt.bar(x, y, width = 0.5) plt.show()
  • 23. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 23/43 In [24]: Explode: Maybe you want one of the wedges to stand out? The explode parameter allows you to do that. The explode parameter, if specified, and not None, must be an array with one value for each wedge. fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.axis('equal') langs = ['C', 'C++', 'Java', 'Python', 'PHP'] students = [23,17,35,29,12] ax.pie(students, labels = langs,autopct='%1.2f%%') plt.show()
  • 24. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 24/43 In [25]: 3D Surface plot Surface plot shows a functional relationship between a designated dependent variable (Y), and two independent variables (X and Z). The plot is a companion plot to the contour plot. A surface plot is like a wireframe plot, but each face of the wireframe is a filled polygon. This can aid perception of the topology of the surface being visualized. The plot_surface() function x,y and z as arguments. y = np.array([35, 25, 25, 15]) mylabels = ["C", "C++", "Python", "Java"] myexplode = [0.2, 0, 0, 0] plt.pie(y, explode = myexplode , labels = mylabels) plt.show()
  • 25. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 25/43 In [26]: from mpl_toolkits import mplot3d x = np.outer(np.linspace(-2, 2, 30), np.ones(30)) y = x.copy().T z = np.cos(x ** 2 + y ** 2) fig = plt.figure() ax = plt.axes(projection='3d') ax.plot_surface(x, y, z,cmap='viridis', edgecolor='none') ax.set_title('Surface plot') plt.show()
  • 26. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 26/43 In [27]: from mpl_toolkits.mplot3d import Axes3D from scipy.stats import multivariate_normal x, y = np.mgrid[-1.0:1.0:30j, -1.0:1.0:30j] xy = np.column_stack([x.flat, y.flat]) mu = np.array([0.0, 0.0]) sigma = np.array([.5, .5]) covariance = np.diag(sigma**2) z = multivariate_normal.pdf(xy, mean=mu, cov=covariance) z = z.reshape(x.shape) fig = plt.figure(num=None, figsize=(10, 10)) ax = fig.add_subplot(111, projection='3d') ax.plot_surface(x,y,z) plt.show()
  • 27. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 27/43 Seaborn Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics.
  • 28. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 28/43 In [28]: Out[28]: <seaborn.axisgrid.PairGrid at 0x7f94b6a11dd0> import seaborn as sns df = sns.load_dataset("penguins") sns.pairplot(df, hue="species")
  • 29. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 29/43 In [29]: Working with Images The image module in Matplotlib package provides functionalities required for loading, rescaling and displaying image. Loading image data is supported by the Pillow library and Matplotlib relies on the Pillow library to load image data. The imread() function is used to read image data in an ndarray object of float32 dtype. tips = sns.load_dataset("tips") g = sns.jointplot(x="total_bill", y="tip", data=tips, kind="reg", truncate=False, xlim=(0, 60), ylim=(0, 12), color="m", height=7)
  • 30. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 30/43 In [30]: In [31]: Get image size (width, height, dimension) import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg from matplotlib.pyplot import figure img = mpimg.imread('mpl.png') figure(num=None, figsize=(10, 10)) imgplot = plt.imshow(img) plt.imsave("logo.png", img, origin = 'lower') newimg = mpimg.imread('logo.png') imgplot = plt.imshow(newimg)
  • 31. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 31/43 In [32]: (512, 512, 3) img_lena = mpimg.imread('lena.png') print(img_lena.shape)
  • 32. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 32/43 In [33]: figure(num=None, figsize=(15, 10)) plt.subplot(2, 2, 1) plt.axis('off') plt.imshow(img_lena[:,:,:]) plt.title("Orginal image") plt.subplot(2, 2, 2) plt.axis('off') red_img_lena = img_lena[:,:,0] plt.imshow(red_img_lena) plt.title("Red Chanel") plt.subplot(2, 2, 3) plt.axis('off') green_img_lena = img_lena[:,:,1] plt.imshow(green_img_lena) plt.title("Green Chanel") plt.subplot(2, 2, 4) plt.axis('off') blue_img_lena = img_lena[:,:,2] plt.imshow(blue_img_lena) plt.title("Blue Chanel") plt.suptitle(" images") plt.show()
  • 33. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 33/43 Examining a specific data range Sometimes you want to enhance the contrast in your image, or expand the contrast in a particular region while sacrificing the detail in colors that don't vary much, or don't matter. A good tool to find interesting regions is the histogram. To create a histogram of our image data, we use the hist() function.
  • 34. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 34/43 In [34]: figure(num=None, figsize=(15, 10)) plt.subplot(2, 2, 1) plt.hist(img_lena.ravel(), bins=256, range=(0.0, 1.0),color = 'Black') plt.title("lena image histogram") plt.subplot(2, 2, 2) plt.hist(red_img_lena.ravel(), bins=256, range=(0.0, 1.0), color = 'red') plt.title("red chanel of lena image histogram") plt.subplot(2, 2, 3) plt.hist(green_img_lena.ravel(), bins=256, range=(0.0, 1.0),color = 'Green' plt.title("green chanel of lena image histogram") plt.subplot(2, 2, 4) plt.hist(blue_img_lena.ravel(), bins=256, range=(0.0, 1.0), color = 'Blue') plt.title("blue chanel of lena image histogram") plt.suptitle(" images histogram") plt.show()
  • 35. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 35/43 In color images, we have 3 color channels representing RGB. In Combined Color Histogram the intensity count is the sum of all three color channels. In [35]: Histogram equalization Histogram equalization is a method in image processing of contrast adjustment using the image's histogram. import matplotlib.pyplot as plt image = plt.imread('lena.png') _ = plt.hist(image.ravel(), bins = 256, color = 'orange', ) _ = plt.hist(image[:, :, 0].ravel(), bins = 256, color = 'red', alpha = 0.5 _ = plt.hist(image[:, :, 1].ravel(), bins = 256, color = 'Green', alpha = 0 _ = plt.hist(image[:, :, 2].ravel(), bins = 256, color = 'Blue', alpha = 0. _ = plt.xlabel('Intensity Value') _ = plt.ylabel('Count') _ = plt.legend(['Total', 'Red_Channel', 'Green_Channel', 'Blue_Channel']) plt.show()
  • 36. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 36/43 In [40]: # Importing Image and ImageOps module from PIL package from PIL import Image, ImageOps figure(num=None, figsize=(15, 10)) im1 = Image.open(r"lena.png") im2 = ImageOps.equalize(im1, mask = None) plt.axis('off') plt.imshow(im2) plt.show()
  • 37. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 37/43 In [41]: Out[41]: Text(0.5, 1.0, 'after histogram eq ') import cv2 import numpy as np from matplotlib import pyplot as plt figure(num=None, figsize=(15, 10)) img_cv = cv2.imread('lena.png',0) equ_cv = cv2.equalizeHist(img_cv) plt.subplot(2, 2, 1) plt.axis('off') plt.imshow(img_cv) plt.subplot(2, 2, 2) plt.axis('off') plt.imshow(equ_cv) plt.subplot(2, 2, 3) plt.hist(img_cv.ravel(),256,[0,256]); plt.title("lena image histogram") plt.subplot(2, 2, 4) plt.hist(equ_cv.ravel(),256,[0,256]); plt.title("after histogram eq ")
  • 38. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 38/43 scikit-image scikit-image is a collection of algorithms for image processing. In [43]: NumPy Sometimes you want to enhance the contrast in your image, or expand the contrast in a particular region while sacrificing the detail in colors that don't vary much, or don't matter. A good tool to find interesting regions is the histogram. To create a histogram of our image data, we use the hist() function. Out[43]: <matplotlib.image.AxesImage at 0x7f949f255b50> from skimage import data,filters figure(num=None, figsize=(15, 10)) img_coin = data.coins() edges_coin = filters.sobel(img_coin) plt.subplot(1, 2, 1) plt.axis('off') plt.imshow(img_coin, cmap='gray') plt.subplot(1, 2, 2) plt.axis('off') plt.imshow(edges_coin, cmap='gray')
  • 39. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 39/43 In [44]: Using SciPy for blurring using a Gaussian filter: Out[44]: <matplotlib.image.AxesImage at 0x7f949fbaab50> figure(num=None, figsize=(15, 10)) image_camera = data.camera() plt.subplot(1, 2, 1) plt.axis('off') plt.imshow(image_camera, cmap='gray') mask_camera = image_camera < 87 image_camera[mask_camera]=255 plt.subplot(1, 2, 2) plt.axis('off') plt.imshow(image_camera, cmap='gray')
  • 40. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 40/43 In [45]: exciting small project Out[45]: <matplotlib.image.AxesImage at 0x7f94a010fdd0> from scipy import misc,ndimage figure(num=None, figsize=(15, 10)) ime_face = misc.face() blurred_face = ndimage.gaussian_filter(ime_face, sigma=3) very_blurred = ndimage.gaussian_filter(ime_face, sigma=5) plt.subplot(1, 3, 1) plt.axis('off') plt.imshow(ime_face) plt.subplot(1, 3, 2) plt.axis('off') plt.imshow(blurred_face) plt.subplot(1, 3, 3) plt.axis('off') plt.imshow(very_blurred)
  • 41. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 41/43 In [46]: Out[46]: <matplotlib.legend.Legend at 0x7f949fab9450> import pandas as pd import datetime import pandas_datareader.data as web from pandas import Series, DataFrame figure(num=None, figsize=(15, 10)) start = datetime.datetime(2010, 1, 1) end = datetime.datetime(2017, 1, 11) df = web.DataReader("AAPL", 'yahoo', start, end) close_px = df['Adj Close'] mavg = close_px.rolling(window=100).mean() from matplotlib import style # Adjusting the size of matplotlib import matplotlib as mpl mpl.rc('figure', figsize=(8, 7)) mpl.__version__ # Adjusting the style of matplotlib style.use('ggplot') close_px.plot(label='AAPL') mavg.plot(label='mavg') plt.legend()
  • 42. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 42/43 real data project
  • 43. 11/8/2020 matplotlib - Jupyter Notebook localhost:8888/notebooks/Desktop/erae/matplotlib_mv/matplotlib.ipynb# 43/43 In [1]: MovieWriter imagemagick unavailable; using Pillow instead. import numpy as np from matplotlib import pyplot as plt from matplotlib.animation import FuncAnimation plt.style.use('seaborn-pastel') fig = plt.figure() ax = plt.axes(xlim=(0, 4), ylim=(-2, 2)) line, = ax.plot([], [], lw=3) def init(): line.set_data([], []) return line, def animate(i): x = np.linspace(0, 4, 1000) y = np.sin(2 * np.pi * (x - 0.01 * i)) line.set_data(x, y) return line, anim = FuncAnimation(fig, animate, init_func=init, frames=200, interval=20, blit=True) anim.save('sine_wave.gif', writer='imagemagick')