Matplotlib – Shishir Kant Singh https://shishirkant.com Jada Sir जाड़ा सर :) Thu, 13 Apr 2023 16:55:40 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://shishirkant.com/wp-content/uploads/2020/05/cropped-shishir-32x32.jpg Matplotlib – Shishir Kant Singh https://shishirkant.com 32 32 187312365 Working with Images in Matplotlib https://shishirkant.com/working-with-images-in-matplotlib/?utm_source=rss&utm_medium=rss&utm_campaign=working-with-images-in-matplotlib Thu, 13 Apr 2023 16:55:36 +0000 https://shishirkant.com/?p=3418 In Matploltlib library, The image module is used for adding images in plots and figures.

  • Only PNG images are supported by matplotlib.
  • There are two useful and important methods of the image module imread(it is used to read imagesand imshow (it is used to display the image).

Now we will cover some examples showing how you can work with images:

Example 1:

In the code snippet, we will read the image using imread() and then display the image using imshow():

import matplotlib.pyplot as plt 
import matplotlib.image as img 

testImage = img.imread('C:\\Users\\StudyTonight\\Desktop\\logoo.png') 

plt.imshow(testImage) 

Copy

Following will be the output:

add image as background to matplotlib plot

Example 2:

In the code example given below, we read the image using imread() and then represent it in the form of an array:

import matplotlib.pyplot as plt 
import matplotlib.image as img 

testImage = img.imread('C:\\Users\\StudyTonight\\Desktop\\logoo.png') 

print(testImage) 


[[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]

[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]

[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]

[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]

[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]

[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]



[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]

[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]

[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]

[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]

[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]

[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]]

Example 3:

In the example given below, we will modify all the parameters of the image:

import matplotlib.pyplot as plt 
import matplotlib.image as img 

testImage = img.imread('C:\\Users\\StudyTonight\\Desktop\\logoo.png') 

print(testImage.shape) 

modifiedImage = testImage[50:200, 100:200, 1] 

plt.imshow(modifiedImage) 

In the above code, the height of the image is 150 pixels (that is displayed from the 50th pixel), width is 100 pixels (that is displayed from the 100th pixel) and the mode value is 1.

Following is the output of the above code:

adding image in matplotlib plot

]]>
3418
Mathematical expressions in matplotlib https://shishirkant.com/mathematical-expressions-in-matplotlib/?utm_source=rss&utm_medium=rss&utm_campaign=mathematical-expressions-in-matplotlib Thu, 13 Apr 2023 16:53:49 +0000 https://shishirkant.com/?p=3415 Writing Mathematical Expressions

The subset TeX markup can be used in any matplotlib text string just by placing it inside a pair of dollar signs ($).

  • In order to make subscripts and superscripts use the _ and ^ symbols respectively.
  • To create Fractions, binomials, and stacked numbers you can use \frac{}{}\binom{}{} and \genfrac{}{}{}{}{}{} commands, respectively.
  • Also, the Radicals can be produced with the \sqrt[]{} command.
  • For mathematical symbols the default font is italics.

Let us cover example for more clear understanding.

Using Mathematical Expression:

In the example given below, we will represent subscript and superscript:

r'$\alpha_i> \beta_i$'

import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0.0, 2.0, 0.01)
s = np.cos(1*np.pi*t)

plt.plot(t,s)
plt.title(r'$\alpha_i> \beta_i$', fontsize=20)

plt.text(0.6, 0.6, r'$\mathcal{A}\mathrm{cos}(2 \omega t)$', fontsize = 20)
plt.xlabel('The time (s)')
plt.ylabel('volts (mV)')
plt.show()

Following is the output of the above code:

using mathematical expression matplotlib example
]]>
3415
Working with Text in Matplotlib https://shishirkant.com/working-with-text-in-matplotlib/?utm_source=rss&utm_medium=rss&utm_campaign=working-with-text-in-matplotlib Thu, 13 Apr 2023 16:52:30 +0000 https://shishirkant.com/?p=3412 There is extensive text support in Matplotlib that includes support for mathematical expressions, the Truetype support for raster, and vector outputs, also there is a newline-separated text with arbitrary rotations, and Unicode support.

Working with Text

The Matplotlib library has its own matplotlib.font_manager that is used to implement a cross-platform, W3C compliant font finding algorithm.

  • In this, the user has great control over text properties such as font size, font weight, text location, and color, etc.
  • The Matplotlib library implements a large number of TeX math symbols and commands that provide the support for mathematical expressions anywhere in your figure.

Given below is a list of commands that are used to create text in the Pyplot interface as well as in Object-oriented interface:

pyplot InterfaceObject-Oriented InterfaceDescription
texttextThis command is used to add text at an arbitrary location of the Axes.
annotateannotateThis command is used to add an annotation, having an optional arrow, at an arbitrary location of theAxes.
xlabelset_xlabelThis command is used to add a label to the Axes’s x-axis.
ylabelset_ylabelThis command is used to add a label to the Axes’s y-axis.
titleset_titleThis command is used to add a title to the Axes.
figtexttextThis command is used to add text at an arbitrary location of the Figure.
suptitlesuptitleThis command is used to add a title to the Figure.

All these functions create and return a Text instance, which can be configured with a variety of font and other related properties.

Time For example!!

Now its time to cover an example in which we will add different text info in different styles to our figure:

import matplotlib.pyplot as plt
fig = plt.figure()

ax = fig.add_axes([0,0,1,1])

ax.set_title('axes title')
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')

ax.text(3, 8, 'This is boxed italics text in data coords', style='italic', 
bbox = {'facecolor': 'orange'})

ax.text(2, 6, r'an equation: $E = mc^2$', fontsize = 16)

ax.text(4, 0.05, 'This is colored text in axes coords',
verticalalignment = 'bottom', color = 'maroon', fontsize = 15)

ax.plot([2], [1], 'o')
ax.annotate('annotate', xy = (2, 1), xytext = (3, 4),
arrowprops = dict(facecolor = 'maroon', shrink = 0.05))
ax.axis([0, 10, 0, 10])
plt.show()

Following is the output for the above code:

adding custom style text to matplotlib figure
]]>
3412
Matplotlib 3D Surface Plot – plot_surface() Function https://shishirkant.com/matplotlib-3d-surface-plot-plot_surface-function/?utm_source=rss&utm_medium=rss&utm_campaign=matplotlib-3d-surface-plot-plot_surface-function Thu, 13 Apr 2023 16:50:32 +0000 https://shishirkant.com/?p=3409 In Matplotlib’s mpl_toolkits.mplot3d toolkit there is axes3d present that provides the necessary functions that are very useful in creating 3D surface plots.

The representation of a three-dimensional dataset is mainly termed as the Surface Plot.

  • One thing is important to note that the surface plot provides a relationship between two independent variables that are X and Z and a designated dependent variable that is Y, rather than just showing the individual data points.
  • The Surface plot is a companion plot to the Contour Plot and it is similar to wireframe plot but there is a difference too and it is each wireframe is basically a filled polygon.
  • With the help of this, the topology of the surface can be visualized very easily.

Creation of 3D Surface Plot

To create the 3-dimensional surface plot the ax.plot_surface() function is used in matplotlib.

The required syntax for this function is given below:

ax.plot_surface(X, Y, Z)

In the above syntax, the X and Y mainly indicate a 2D array of points x and y while Z is used to indicate the 2D array of heights.

plot_surface() Attributes

Some attributes of this function are as given below:

1. shade

This attribute is used to shade the face color.

2. facecolors

This attribute is used to indicate the face color of the individual surface

3. vmax

This attribute indicates the maximum value of the map.

4. vmin

This attribute indicates the minimum value of the map.

5. norm

This attribute acts as an instance to normalize the values of color map

6. color

This attribute indicates the color of the surface

7. cmap

This attribute indicates the colormap of the surface

8. rcount

This attribute is used to indicate the number of rows to be used The default value of this attribute is 50

9. ccount

This attribute is used to indicate the number of columns to be used The default value of this attribute is 50

10. rstride

This attribute is used to indicate the array of row stride(that is step size)

11. cstride

This attribute is used to indicate the array of column stride(that is step size)

3D Surface Plot Basic Example

Below we have a code where we will use the above-mentioned function to create a 3D Surface Plot:

from mpl_toolkits import mplot3d 
import numpy as np 
import matplotlib.pyplot as plt 

x = np.outer(np.linspace(-4, 4, 33), np.ones(33)) 
y = x.copy().T
z = (np.sin(x **2) + np.cos(y **2) ) 


fig = plt.figure(figsize =(14, 9)) 
ax = plt.axes(projection ='3d') 

ax.plot_surface(x, y, z) 


plt.show() 

The output for the above code is as follows:

3D surface plot matplotlib basic example

Gradient Surface Plot

This plot is a combination of a 3D surface plot with a 2D contour plot. In the Gradient surface plot, the 3D surface is colored same as the 2D contour plot. The parts that are high on the surface contains different color rather than the parts which are low at the surface.

The required syntax is:

ax.plot_surface(X, Y, Z, cmap, linewidth, antialiased)

where cmap is used to set the color for the surface.

Gradient Surface Plot Example

Now it’s time to cover a gradient surface plot. The code snippet for the same is given below:

from mpl_toolkits import mplot3d 
import numpy as np 
import matplotlib.pyplot as plt 

x = np.outer(np.linspace(-3, 3, 32), np.ones(32)) 
y = x.copy().T 
z = (np.sin(x **2) + np.cos(y **2) ) 

fig = plt.figure(figsize =(14, 9)) 
ax = plt.axes(projection ='3d') 

my_cmap = plt.get_cmap('cool') 

surf = ax.plot_surface(x, y, z, cmap = my_cmap, edgecolor ='none') 

fig.colorbar(surf, ax = ax, shrink = 0.7, aspect = 7) 

ax.set_title('Surface plot') 


plt.show() 

The output for the above code is as follows:

gradient surface plot matplotlib basic example
]]>
3409
Matplotlib 3D WireFrame Plot – plot_wireframe() Function https://shishirkant.com/matplotlib-3d-wireframe-plot-plot_wireframe-function/?utm_source=rss&utm_medium=rss&utm_campaign=matplotlib-3d-wireframe-plot-plot_wireframe-function Thu, 13 Apr 2023 16:48:42 +0000 https://shishirkant.com/?p=3405 For the data visualization using 3D wireframe, we require some modules from matplotlibmpl_toolkits and numpy library.

The wireframe plot basically takes a grid of values and projects it onto the specified 3-dimensional surfaces, and it can help in making the resulting three-dimensional forms quite easy for visualization.

To create the 3D Wireframe plot the plot_wireframe() function will be used.

Now its time to cover few examples for the 3D wireframe plot.

3D Wireframe Plot Basic Example:

Below we have an example where we will create a 3D Wireframe plot:

from mpl_toolkits.mplot3d import axes3d 
from matplotlib import pyplot 

fig = pyplot.figure() 
wf = fig.add_subplot(111, projection='3d') 
x, y, z = axes3d.get_test_data(0.07) 
wf.plot_wireframe(x,y,z, rstride=2, cstride=2, color='maroon') 

wf.set_title('3D wireframe plot') 
pyplot.show() 

Here is the output of the above code:

3d wireframe plot basic example

3D Wireframe Plot Example 2:

Here is another example and code snippet for the same is given below:

from mpl_toolkits import mplot3d 
import numpy 

a = numpy.linspace(-5, 5, 25) 
b = numpy.linspace(-5, 5, 25) 
x, y = numpy.meshgrid(a, b) 
z = numpy.cos(numpy.sqrt(x**2 + y**2)) 

fig = pyplot.figure() 
wf = pyplot.axes(projection ='3d') 
wf.plot_wireframe(x, y, z, color ='blue') 

wf.set_title('Example 2') 
pyplot.show() 

Here is the output of the above code:

]]>
3405
Matplotlib 3D Contour Plot – contour3d() Function https://shishirkant.com/matplotlib-3d-contour-plot-contour3d-function/?utm_source=rss&utm_medium=rss&utm_campaign=matplotlib-3d-contour-plot-contour3d-function Thu, 13 Apr 2023 16:47:21 +0000 https://shishirkant.com/?p=3402 To draw or to enable the 3d plots you just need to import the mplot3d toolkit.

There is a function named ax.contour3D() that is used to create a three-dimensional contour plot.

This function requires all the input data to be in the form of two-dimensional regular grids, with its Z-data evaluated at each point.

3D Contour Plot Example

In the example given below, we will create a 3-dimensional contour plot for the sine function. The code snippet is as given below:

from mpl_toolkits import mplot3d 
import numpy as np 
import matplotlib.pyplot as plt 
from matplotlib import cm 
import math 

x = [i for i in range(0, 200, 100)] 
y = [i for i in range(0, 200, 100)] 

X, Y = np.meshgrid(x, y) 
Z = [] 
for i in x: 
    t = [] 
    for j in y: 
        t.append(math.sin(math.sqrt(i*2+j*2))) 
    Z.append(t) 

fig = plt.figure() 
ax = plt.axes(projection='3d') 
ax.contour3D(X, Y, Z, 50, cmap=cm.cool) 
ax.set_xlabel('a') 
ax.set_ylabel('b') 
ax.set_zlabel('c') 
ax.set_title('3D contour Plot for sine') 
plt.show() 

The explanation of the functions used in the above code is as follows:

  • meshgridThis is a function of NumPy library that is used to create a rectangular grid out of two given one-dimensional arrays representing the Cartesian or Matrix indexing.
  • plt.axes()This function is used to create the object of the Axes.
  • ax.contour3DThis function is used to create contour
  • ax.set_xlabelThis function is used to set the label for the x-axis
  • ax.set_title()This function is used to provide a title to the Plot

Following will be the output of the above code:

3d contour plot matplotlib
]]>
3402
Matplotlib 3D Plotting – Line and Scatter Plot https://shishirkant.com/matplotlib-3d-plotting-line-and-scatter-plot/?utm_source=rss&utm_medium=rss&utm_campaign=matplotlib-3d-plotting-line-and-scatter-plot Thu, 13 Apr 2023 16:45:58 +0000 https://shishirkant.com/?p=3397 It is important to note that Matplotlib was initially designed with only two-dimensional plotting in mind. But later on, some three-dimensional plotting utilities were built on top of Matplotlib’s two-dimensional display, which provides a set of tools for three-dimensional data visualization in matplotlib.

Also, a 2D plot is used to show the relationships between a single pair of axes that is x and y whereas the 3D plot, on the other hand, allows us to explore relationships of 3 pairs of axes that is x-y, x-z, and y-z

Three Dimensional Plotting

The 3D plotting in Matplotlib can be done by enabling the utility toolkit. The utility toolkit can be enabled by importing the mplot3d library, which comes with your standard Matplotlib installation via pip.

After importing this sub-module, 3D plots can be created by passing the keyword projection="3d" to any of the regular axes creation functions in Matplotlib.

Let us cover some examples for three-dimensional plotting using this submodule in matplotlib.

3D Line Plot

Here is the syntax to plot the 3D Line Plot:

Axes3D.plot(xs, ys, *args, **kwargs)

With the code snippet given below we will cover the 3D line plot in Matplotlib:

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = plt.axes(projection='3d')
z = np.linspace(0, 1, 100)
x = z * np.sin(30 * z)
y = z * np.cos(30 * z)

ax.plot3D(x, y, z, 'maroon')
ax.set_title('3D line plot')
plt.show()

Following is the output for it:

3d line plot example matplotlib

3D Scatter Plot

Here is the syntax for 3D Scatter Plot:

Axes3D.scatter(xs, ys, zs=0, zdir='z', s=20, c=None, depthshade=True, *args, **kwargs)

Arguments

ArgumentDescription
xsysThese two arguments indicate the position of data points.
zsIt can be Either an array of the same length as xs and ys or it can be a single value to place all points in the same plane. The default value of this argument is 0.
zdirThis Argument is used to indicate which direction to use as z (‘x’, ‘y’ or ‘z’) at the time of plotting a 2D set.
sThis argument is used to indicate the Size in points. It can either be a scalar or an array of the same length as x and y.
cThis argument is used to indicate the color.
depthshadeThis argument is used to tell Whether or not to shade the scatter markers in order to give the appearance of depth. The default value of this argument is True.

With the code snippet given below we will cover the 3D Scatter plot in Matplotlib:

fig = plt.figure()
ax = plt.axes(projection="3d")

z_line = np.linspace(0, 15, 500)
x_line = np.cos(z_line)
y_line = np.sin(z_line)
ax.plot3D(x_line, y_line, z_line, 'blue')

z_points = 15 * np.random.random(500)
x_points = np.cos(z_points) + 0.1 * np.random.randn(500)
y_points = np.sin(z_points) + 0.1 * np.random.randn(500)
ax.scatter3D(x_points, y_points, z_points, c=z_points, cmap='hsv');

plt.show()

The output is:

scatter 3D plot example matplotlib
]]>
3397
Matplotlib Box Plot – boxplot() Function https://shishirkant.com/matplotlib-box-plot-boxplot-function/?utm_source=rss&utm_medium=rss&utm_campaign=matplotlib-box-plot-boxplot-function Thu, 13 Apr 2023 16:06:07 +0000 https://shishirkant.com/?p=3385 The box plot in matplotlib is mainly used to displays a summary of a set of data having properties like minimum, first quartile, median, third quartile, and maximum.

  • The Box Plot is also known as Whisker Plot.
  • The box is created from the first quartile to the third quartile in the box plot, also there is a verticle line going through the box at the median.
  • In the Box Plot, the x-axis indicates the data to be plotted while the y-axis denotes the frequency distribution.

Creating the Box Plot

The Box plot in the matplotlib library is usually created with the help of boxplot() function.

  • In the Box Plot the numpy.random.normal() is used to create some random data, it takes mean, standard deviation, and the desired number of values as its arguments.
  • The provided data values to the ax.boxplot() method can be a Numpy array or Python list or it can be Tuple of arrays

The required syntax for the boxplot() function is as follows:

matplotlib.pyplot.boxplot(data, notch, vert, patch_artist, widths)

Following are the parameters of this function:

  • dataThis parameter indicates the array or sequence of arrays needed to plot.
  • notchThis is an optional parameter that accepts boolean values. It has None as default value.
  • vertThis is an optional parameter that accepts boolean values that is false for horizontal plot and true for vertical plot respectively.
  • patch_artistThis is an optional parameter having boolean value with None as its default value
  • widthsThis is an optional parameter that accepts an array and used to set the width of boxes. The default value is None.

Now we will dive into some examples of creating a Box plot.

Creating a Box Plot Example:

The code for creating a simple Box plot in the Matplotlib library is as follows:

import matplotlib.pyplot as plt
 
value1 = [84,77,20,40,67,62,75,78,71,32,98,89,78,67,72,82,87,66,56,52]
value2=[62,5,91,25,35,32,96,99,3,90,95,34,27,55,100,15,71,11,37,21]
value3=[23,89,12,78,72,89,25,69,68,86,19,48,15,16,16,75,65,31,25,52]
value4=[59,73,73,16,81,61,88,98,10,87,29,72,16,23,72,88,78,99,75,30]
 
box_plot_data=[value1,value2,value3,value4]
plt.boxplot(box_plot_data)
plt.show()

Here is the output:

box plot matplotlib example

Creating a Box plot with Fills and Labels:

In the code snippet given below, we will provide a label to the box plot and will fill the box plot. Let us see the code for the example:

import matplotlib.pyplot as plt
 
value1 = [82,76,24,40,67,62,75,78,71,32,98,89,78,67,72,82,87,66,56,52]
value2=[62,5,91,25,36,32,96,95,3,90,95,32,27,55,100,15,71,11,37,21]
value3=[23,89,12,78,72,89,25,69,68,86,19,49,15,16,16,75,65,31,25,52]
value4=[59,73,70,16,81,61,88,98,10,87,29,72,16,23,72,88,78,99,75,30]
 
box_plot_data=[value1,value2,value3,value4]
plt.boxplot(box_plot_data,patch_artist=True,labels=['subject1','subject2','subject3','subject4'])
plt.show()

Here is the output:

box plot matplotlib example

Creating a Box plot with Notch:

In this example, we will plot a box plot having a notch.

import matplotlib.pyplot as plt
 
value1 = [84,76,24,46,67,62,78,78,71,38,98,89,78,69,72,82,87,68,56,59]
value2=[62,5,91,25,39,32,96,99,3,98,95,32,27,55,100,15,71,11,37,29]
value3=[23,89,12,78,72,89,25,69,68,86,19,49,15,16,16,75,65,31,25,52]
value4=[59,73,70,16,81,61,88,98,10,87,29,72,16,23,72,88,78,99,75,30]
 
box_plot_data=[value1,value2,value3,value4]
plt.boxplot(box_plot_data,notch='True',patch_artist=True,labels=['subject1','subject2','subject3','subject4'])
plt.show()

Here is the output:

box plot matplotlib example

Time For Live Example!

In this live example, we will draw a horizontal box plot having different colors.

]]>
3385
Matplotlib Quiver Plot – quiver() Function https://shishirkant.com/matplotlib-quiver-plot-quiver-function/?utm_source=rss&utm_medium=rss&utm_campaign=matplotlib-quiver-plot-quiver-function Thu, 13 Apr 2023 16:02:59 +0000 https://shishirkant.com/?p=3380

To plot the 2D field of arrows, we use the Quiver plot in the matplotlib library.

  • This plot mainly helps in displaying the velocity vectors as arrows having components (u,v) at the points (x,y).
  • The Quiver plots are useful for Electrical engineers to visualize electrical potential and for Mechanical engineers to show stress gradients.

Creating Matplotlib Quiver Plot

In order to create a Quiver Plot the ax.quiver() function is used.

The required syntax to use this function is as follows:

ax.quiver(x_pos, y_pos, x_dir, y_dir, color) 

Following are the parameters of this function, which you can see above in the syntax:

  • x_pos and y_posThese two parameters of the function are used to indicate the starting position of the arrows.
  • x_dir and y_dirThese two parameters of the function are used to indicate the directions of the arrows.
  • colorThis parameter is used to specify the color of the Quiver Plot.

Let us now dive into some examples related to this.

Simple Quiver Plot Example:

In the example given below, we will cover how to plot a Quiver plot with a single arrow:

import numpy as np 
import matplotlib.pyplot as plt 

x_pos = 0
y_pos = 0
x_direct = 1
y_direct = 1

fig, ax = plt.subplots(figsize = (10, 7)) 
ax.quiver(x_pos, y_pos, x_direct, y_direct) 
ax.set_title('Quiver plot with a single arrow') 

plt.show() 

Here is the output:

single arrow quiver plot matplotlib example

Two Arrow Quiver Plot Example:

In the example given below, we will cover how to plot a Quiver plot with two arrows:

import numpy as np 
import matplotlib.pyplot as plt 

x_pos = [0, 0] 
y_pos = [0, 0] 
x_direct = [1, 0] 
y_direct = [1, -1] 

fig, ax = plt.subplots(figsize = (12, 7)) 
ax.quiver(x_pos, y_pos, x_direct, y_direct,scale = 8) 

ax.axis([-1.5, 1.5, -1.5, 1.5]) 

plt.show() 

Here is the output:

two arrow quiver plot matplotlib example

Time for Live Example!

Now we will cover a live example where we will draw the Quiver plot using meshgrid:

]]>
3380
Matplotlib Contour Plot – contour() Function https://shishirkant.com/matplotlib-contour-plot-contour-function/?utm_source=rss&utm_medium=rss&utm_campaign=matplotlib-contour-plot-contour-function Thu, 13 Apr 2023 15:59:38 +0000 https://shishirkant.com/?p=3374 To create a visualization of 3-Dimensional plots in 2-Dimensional space we use contour plots in Matplotlib. Contour plots are also known as Level Plots.

  • Suppose there are two variables X and Y and you want to plot them then the response of two variables will be Z and it will be plotted as slices on the X-Y plane due to which contours are also referred to as Z-slices or iso-response.
  • We should use contour plot if you want to see how the value of Z changes as a function of two inputs that is X and Y, like this Z = f(X,Y).
  • A contour line or isoline of a function of two variables is basically a curve along which the function has a constant value.
  • There are two functions in Matplotlib that is contour()(this is used to draw the contour lines) and contourf()(this is used to draw filled contours).

Uses of Contour Plot:

There are some uses of contour plot given below:

  • To visualize density.
  • To visualize the meteorological department.
  • To visualize the heights of mountains.

Matplotlib contour() Function

The function matplotlib.pyplot.contour() is useful when Z = f(X, Y) here, Z changes as a function of input X and Y.

contourf() function is also available in matplotlib which allows us to draw filled contours.

This method returns a QuadContourSet. The required syntax for the same is given below:

 matplotlib.pyplot.contour([X, Y, ] Z, [levels], **kwargs)

Let us discuss the parameters of this function:

1. X, Y

This parameter indicates 2-D NumPy arrays with having same shape as Z or same like 1-D arrays in a manner such that len(X)==M and len(Y)==N (where M are rows and N are columns of Z)

2. Z

This parameter indicates the height values over which the contour is drawn. The shape is (M, N).

3. levels

This parameter is used to determine the number and position of the contour lines.

Let us cover some Examples of this function.

Simple Contour Lines Example:

In this example we will plot contour lines with the help of contour() function:

Let’s take another example for contour plot.

Filled Contour Plot Example:

Now let us draw a filled contour with the help of contourf() function:

]]>
3374