Matplotlib – Multiprocessing

Matplotlib – Multiprocessing ”; Previous Next Multiprocessing is a technique used to execute multiple processes concurrently, taking advantage of multi-core processors. In Python, the multiprocessing module provides a convenient way to create and manage parallel processes. This is useful for tasks that can be parallelized, such as generating plots, running simulations, or performing computations on large datasets. Multiprocessing in Matplotlib Matplotlib is traditionally used in a single-threaded manner, combining it with the multiprocessing library allows for the creation of plots in parallel. This can be useful when dealing with a large number of plots or computationally intensive tasks. Creating Multiple Matplotlib Plots Creating multiple plots sequentially can lead to a slower execution, especially when dealing with a large number of plots. In such cases, using the multiprocessing technique can significantly improve performance by allowing the creation of multiple plots concurrently. Example Let”s see a basic example that demonstrates how to create multiple Matplotlib plots in parallel using multiprocessing. import matplotlib.pyplot as plt import numpy as np import multiprocessing def plot(datax, datay, name): x = datax y = datay**2 plt.scatter(x, y, label=name) plt.legend() plt.show() def multiP(): for i in range(4): p = multiprocessing.Process(target=plot, args=(i, i, i)) p.start() if __name__ == “__main__”: input(”Press Enter to start parallel plotting…”) multiP() Output On executing the above program, 4 matplotlib plots are created in parallel see the video below for reference − Saving Multiple Matplotlib Figures Saving multiple Matplotlib figures concurrently is another scenario where multiprocessing can be advantageous. Example 1 Here is an example that uses multiprocessing to save multiple Matplotlib figures concurrently. import matplotlib.pyplot as plt import numpy.random as random from multiprocessing import Pool def do_plot(number): fig = plt.figure(number) a = random.sample(1000) b = random.sample(1000) # generate random data plt.scatter(a, b) plt.savefig(“%03d.jpg” % (number,)) plt.close() print(f”Image {number} saved successfully…”) if __name__ == ”__main__”: pool = Pool() pool.map(do_plot, range(1, 5)) Output On executing the above code we will get the following output − Image 1 saved successfully… Image 2 saved successfully… Image 3 saved successfully… Image 4 saved successfully… If you navigate to the directory where the plots were saved, you will be able to observe the ved 001.jpg, 002.jpg, 003.jpg, and 004.jpg images as shown below − Example 2 Here is another example that demonstrates how to use multiprocessing to generate data in one process and plot it in another using Matplotlib. import multiprocessing as mp import time import matplotlib.pyplot as plt import numpy as np # Fixing random state for reproducibility np.random.seed(19680801) class ProcessPlotter: def __init__(self): self.x = [] self.y = [] def terminate(self): plt.close(”all”) def call_back(self): while self.pipe.poll(): command = self.pipe.recv() if command is None: self.terminate() return False else: self.x.append(command[0]) self.y.append(command[1]) self.ax.plot(self.x, self.y, ”ro”) self.fig.canvas.draw() return True def __call__(self, pipe): print(”Starting plotter…”) self.pipe = pipe self.fig, self.ax = plt.subplots() timer = self.fig.canvas.new_timer(interval=1000) timer.add_callback(self.call_back) timer.start() print(”…done”) plt.show() class NBPlot: def __init__(self): self.plot_pipe, plotter_pipe = mp.Pipe() self.plotter = ProcessPlotter() self.plot_process = mp.Process( target=self.plotter, args=(plotter_pipe,), daemon=True) self.plot_process.start() def plot(self, finished=False): send = self.plot_pipe.send if finished: send(None) else: data = np.random.random(2) send(data) # Main function for the integrated code def main_with_multiprocessing(): pl = NBPlot() for _ in range(10): pl.plot() time.sleep(0.5) pl.plot(finished=True) if __name__ == ”__main__”: if plt.get_backend() == “MacOSX”: mp.set_start_method(“forkserver”) input(”Press Enter to start integrated example…”) main_with_multiprocessing() Output On executing the above program, will generate the matplotlib plots with random data see the video below for reference − Print Page Previous Next Advertisements ”;

Matplotlib – Tick Locators

Matplotlib – Tick Locators ”; Previous Next In general graphs and plottings, ticks play a crucial role in representing the scale of x and y-axes through small lines, offering a clear indication of the associated values. Tick locators, on the other hand, define the positions of these ticks along the axis, offering a visual representation of the scale. The below image represents the major and minor ticks on a graph − Tick Locators in Matplotlib Matplotlib provides a mechanism for controlling the positioning of ticks on axes through its tick locators. The matplotlib.ticker module contains classes for configuring tick locating and formatting. These classes include generic tick locators, Formatters, and domain-specific custom ones. While locators are unaware of major or minor ticks, they are used by the Axis class to support major and minor tick locating and formatting. Different Tick Locators The matplotlib provides different tick locator within its ticker module, allowing users to customize the tick positions on axes. Some of the Tick Locators include − AutoLocator MaxNLocator LinearLocator LogLocator MultipleLocator FixedLocator IndexLocator NullLocator SymmetricalLogLocator AsinhLocator LogitLocator AutoMinorLocator Defining Custom Locators Basic Setup Before diving into specific tick locators, let”s establish a common setup function to draw the plot with ticks. import matplotlib.pyplot as plt import numpy as np import matplotlib.ticker as ticker def draw_ticks(ax, title): # it shows the bottom spine only ax.yaxis.set_major_locator(ticker.NullLocator()) ax.spines[[”left”, ”right”, ”top”]].set_visible(False) ax.xaxis.set_ticks_position(”bottom”) ax.tick_params(which=”major”, width=1.00, length=5) ax.tick_params(which=”minor”, width=0.75, length=2.5) ax.set_xlim(0, 5) ax.set_ylim(0, 1) ax.text(0.0, 0.2, title, transform=ax.transAxes, fontsize=14, fontname=”Monospace”, color=”tab:blue”) Now, let”s explore the working of each tick locator. Auto Locator The AutoLocator and AutoMinorLocator are used for automatically determining the positions of major and minor ticks on an axis, respectively. Example This example demonstrates how to use the AutoLocator and AutoMinorLocator to automatically handle the positioning of major and minor ticks on an axis. # Auto Locator fig, ax = plt.subplots(1,1,figsize=(7,1.5), facecolor=”#eaffff”) plt.subplots_adjust(bottom=0.3, top=0.6, wspace=0.2, hspace=0.4) draw_ticks(ax, title=”AutoLocator() and AutoMinorLocator()”) ax.xaxis.set_major_locator(ticker.AutoLocator()) ax.xaxis.set_minor_locator(ticker.AutoMinorLocator()) ax.set_title(”Auto Locator and Auto Minor Locator”) plt.show() Output Null Locator The NullLocator places no ticks on the axis. Example Let’s see the following example for working of the NullLocator. # Null Locator fig, ax = plt.subplots(1,1,figsize=(7,1.5), facecolor=”#eaffff”) plt.subplots_adjust(bottom=0.3, top=0.6, wspace=0.2, hspace=0.4) draw_ticks(ax, title=”NullLocator()”) ax.xaxis.set_major_locator(ticker.NullLocator()) ax.xaxis.set_minor_locator(ticker.NullLocator()) ax.set_title(”Null Locator (No ticks)”) plt.show() Output Multiple Locator The MultipleLocator() class allows ticks to be positioned at multiples of a specified base, supporting both integer and float values. Example The following example demonstrates how to use the MultipleLocator() class. # Multiple Locator fig, ax = plt.subplots(1,1,figsize=(7,1.5), facecolor=”#eaffff”) plt.subplots_adjust(bottom=0.3, top=0.6, wspace=0.2, hspace=0.4) draw_ticks(ax, title=”MultipleLocator(0.5)”) ax.xaxis.set_major_locator(ticker.MultipleLocator(0.5)) ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.1)) ax.set_title(”Multiple Locator”) plt.show() Output Fixed Locator The FixedLocator() places ticks at specified fixed locations. Example Here is an example of using the FixedLocator() class. # Fixed Locator fig, ax = plt.subplots(1,1,figsize=(7,1.5), facecolor=”#eaffff”) plt.subplots_adjust(bottom=0.3, top=0.6, wspace=0.2, hspace=0.4) draw_ticks(ax, title=”FixedLocator([0, 1, 3, 5])”) ax.xaxis.set_major_locator(ticker.FixedLocator([0, 1, 3, 5])) ax.xaxis.set_minor_locator(ticker.FixedLocator(np.linspace(0.2, 0.8, 4))) ax.set_title(”Fixed Locator”) plt.show() Output Linear Locator The LinearLocator spaces ticks evenly between specified minimum and maximum values. Example Here is an example that applies the Linear Locator to the major and minor ticks of an axes. # Linear Locator fig, ax = plt.subplots(1,1,figsize=(7,1.5), facecolor=”#eaffff”) plt.subplots_adjust(bottom=0.3, top=0.6, wspace=0.2, hspace=0.4) draw_ticks(ax, title=”LinearLocator(numticks=3)”) ax.xaxis.set_major_locator(ticker.LinearLocator(3)) ax.xaxis.set_minor_locator(ticker.LinearLocator(10)) ax.set_title(”Linear Locator”) plt.show() Output Index Locator This locator is suitable for index plots, where x = range(len(y)). Example Here is an example that uses the index loctator (ticker.IndexLocator() class). # Index Locator fig, ax = plt.subplots(1,1,figsize=(7,1.5), facecolor=”#eaffff”) plt.subplots_adjust(bottom=0.3, top=0.6, wspace=0.2, hspace=0.4) draw_ticks(ax, title=”IndexLocator(base=0.5, offset=0.25)”) ax.plot([0]*5, color=”white”) ax.xaxis.set_major_locator(ticker.IndexLocator(base=0.5, offset=0.25)) ax.set_title(”Index Locator”) plt.show() Output MaxN Locator The MaxNLocator finds up to a maximum number of intervals with ticks at nice locations. Example Here is an example of using the MaxNLocator() class for both major and minor ticks. # MaxN Locator fig, ax = plt.subplots(1,1,figsize=(7,1.5), facecolor=”#eaffff”) plt.subplots_adjust(bottom=0.3, top=0.6, wspace=0.2, hspace=0.4) draw_ticks(ax, title=”MaxNLocator(n=4)”) ax.xaxis.set_major_locator(ticker.MaxNLocator(4)) ax.xaxis.set_minor_locator(ticker.MaxNLocator(40)) ax.set_title(”MaxN Locator”) plt.show() Output Log Locator The LogLocator is used for spacing ticks logarithmically from min to max. Example Let”s see an example of using the Log Locator. It shows the minor tick labels on a log-scale. # Log Locator fig, ax = plt.subplots(1,1,figsize=(7,1.5), facecolor=”#eaffff”) plt.subplots_adjust(bottom=0.3, top=0.6, wspace=0.2, hspace=0.4) draw_ticks(ax, title=”LogLocator(base=10, numticks=15)”) ax.set_xlim(10**3, 10**10) ax.set_xscale(”log”) ax.xaxis.set_major_locator(ticker.LogLocator(base=10, numticks=15)) ax.set_title(”Log Locator”) plt.show() Output Print Page Previous Next Advertisements ”;

Matplotlib – Dateticks

Matplotlib – Dateticks ”; Previous Next In general plotting, dateticks refer to the labels of the tick lines or markers on the axes of a plot with dates or times, replacing the default numeric values. This feature is especially useful when dealing with time series data. The image below illustrates Dateticks on a plot − Dateticks in Matplotlib Matplotlib provides powerful tools for plotting time-series data, allowing users to represent dates or times instead of the default numeric values on the tick lines or markers (dateticks). The library simplifies the process of working with dates by converting date instances into days since the default epoch (1970-01-01T00:00:00). This conversion, along with tick locating and formatting, occurs in the background, making it transparent to the user. The matplotlib.dates module plays a key role in handling various date-related functionalities. This includes converting data to datetime objects, formatting dateticks labels, and setting the frequency of ticks. Basic Dateticks with DefaultFormatter Matplotlib sets the default tick locator and formatter for the axis, using the AutoDateLocator and AutoDateFormatter classes respectively. Example This example demonstrates the plotting of time-series data, here Matplotlib handles the date formatting automatically. import numpy as np import matplotlib.pylab as plt # Generate an array of dates times = np.arange(np.datetime64(”2023-01-02”), np.datetime64(”2024-02-03”), np.timedelta64(75, ”m”)) # Generate random data for y axis y = np.random.randn(len(times)) # Create subplots fig, ax = plt.subplots(figsize=(7,4), facecolor=”.9”) ax.plot(times, y) ax.set_xlabel(”Dataticks”,color=”xkcd:crimson”) ax.set_ylabel(”Random data”,color=”xkcd:black”) plt.show() Output On executing the above code we will get the following output − Customizing Dateticks with DateFormatter For manual customization of date formats, Matplotlib provides the DateFormatter module, which allows users to change the format of dateticks. Example This example demonstrates how to manually customize the format of Dateticks. import numpy as np import matplotlib.pylab as plt import matplotlib.dates as mdates # Generate an array of dates times = np.arange(np.datetime64(”2023-01-02”), np.datetime64(”2024-02-03”), np.timedelta64(75, ”m”)) # Generate random data for y axis y = np.random.randn(len(times)) # Create subplots fig, ax = plt.subplots(figsize=(7,5)) ax.plot(times, y) ax.set_title(”Customizing Dateticks using DateFormatter”) ax.xaxis.set_major_formatter(mdates.DateFormatter(”%Y-%b”)) # Rotates and right-aligns the x labels so they don”t overlap each other. for label in ax.get_xticklabels(which=”major”): label.set(rotation=30, horizontalalignment=”right”) plt.show() Output On executing the above code we will get the following output − Advanced Formatting with ConciseDateFormatter The ConciseDateFormatter class in Matplotlib simplifies and enhances the appearance of dateticks. This formatter is designed to optimize the choice of strings for tick labels and minimizes their length, which often removes the need to rotate the labels. Example This example uses the ConciseDateFormatter and AutoDateLocator classes to set the best tick limits and date formats for the plotting. import datetime import matplotlib.pyplot as plt import matplotlib.dates as mdates import numpy as np # Define a starting date base_date = datetime.datetime(2023, 12, 31) # Generate an array of dates with a time delta of 2 hours num_hours = 732 dates = np.array([base_date + datetime.timedelta(hours=(2 * i)) for i in range(num_hours)]) date_length = len(dates) # Generate random data for the y-axis np.random.seed(1967801) y_axis = np.cumsum(np.random.randn(date_length)) # Define different date ranges date_ranges = [ (np.datetime64(”2024-01”), np.datetime64(”2024-03”)), (np.datetime64(”2023-12-31”), np.datetime64(”2024-01-31”)), (np.datetime64(”2023-12-31 23:59”), np.datetime64(”2024-01-01 13:20”)) ] # Create subplots for each date range figure, axes = plt.subplots(3, 1, constrained_layout=True, figsize=(6, 6)) for nn, ax in enumerate(axes): # AutoDateLocator and ConciseDateFormatter for date formatting locator = mdates.AutoDateLocator(minticks=3, maxticks=7) formatter = mdates.ConciseDateFormatter(locator) ax.xaxis.set_major_locator(locator) ax.xaxis.set_major_formatter(formatter) # Plot the random data within the specified date range ax.plot(dates, y_axis) ax.set_xlim(date_ranges[nn]) axes[0].set_title(”Concise Date Formatter”) # Show the plot plt.show() Output On executing the above code we will get the following output − Print Page Previous Next Advertisements ”;

Matplotlib – Axes Class

Matplotlib – Axes Class ”; Previous Next In the context of Matplotlib, axes does not refer to the plural form of an axis. Instead, it represents the entire plotting area on a figure or canvas. Which includes the x-axis, y-axis, plotting data, ticks, ticks labels, and more. Refer to the image below − Consider the figure where two Axes objects are created using the ax = fig.subplots() method. The first axes display exponential data, while the second axes show a sine wave. Each Axes (subplot) has its own set of labels, ticks, and legends, providing a distinct representation within the same figure. Axes class in matplotlib The Axes() class serves as the gateway to creating data visualizations. Once an Axes object is instantiated on a figure, a variety of methods become available to add and manipulate data within that plotting area. This class is part of the matplotlib.axes module, providing fundamental functionalities to work with the Matplotlib object-oriented programming (OOP) interface. Most of the essential plotting methods are defined on the Axes class, making it a central component for customizing and enhancing visualizations. Creating an Axes Creating an Axes object is typically the first step in Matplotlib plotting. This can be done through methods on Figure object like Figure.subplots(), Figure.add_axes(), or via the pyplot interface function, pyplot.subplots(). These methods provides the creation of one or more Axes objects in a figure. Example The following example uses the pyplot.subplot() method to creat two axes on a figure. The subplots() method is useful for generating the axes instance. import matplotlib.pyplot as plt import numpy as np # Creating a 1×2 subplot layout fig, (axes1, axes2) = plt.subplots(1, 2, figsize=(7, 4), layout=”constrained”) # Adding labels to each subplot axes1.annotate(”axes1”, (0.5, 0.5),transform=axes1.transAxes, ha=”center”, va=”center”, fontsize=18, color=”darkgrey”) axes2.annotate(”axes2”, (0.5, 0.5),transform=axes2.transAxes, ha=”center”, va=”center”, fontsize=18, color=”darkgrey”) fig.suptitle(”Creating Two Axes on a Figure”) # Displaying the plot plt.show() Output On executing the above code we will get the following output − Changing an Axes properties To set the properties of an axes, you have to access the axes object, after that you can use various `set_*` methods to modify its properties. Example import matplotlib.pyplot as plt import numpy as np # Creating a 1×2 subplot layout fig, (axes1, axes2) = plt.subplots(1, 2, figsize=(7, 4), constrained_layout=True) # Changing the properties of the first axes axes1.set_xlabel(“X-axis”) # Set label for X-axis axes1.set_ylabel(“Y-axis”) # Set label for Y-axis axes1.set_facecolor(”lightgreen”) # Setting background color axes1.annotate(”axes1”, (0.5, 0.5), transform=axes1.transAxes, ha=”center”, va=”center”, fontsize=18, color=”darkgrey”) axes2.set_title(”Second axes”) axes2.annotate(”axes2”, (0.5, 0.5), transform=axes2.transAxes, ha=”center”, va=”center”, fontsize=18, color=”darkgrey”) # Adding a title to the figure fig.suptitle(”Changing Axes Properties”) # Displaying the plot plt.show() Output On executing the above code you will get the following output − Plotting on an Axes This class offers several high-level plotting methods to create different plot on axes. Example Here is an example uses the Axes.plot() method to create a line plot representing the sin(x). import matplotlib.pyplot as plt import numpy as np # Sample Data x = np.linspace(0, 2 * np.pi, 400) y = np.sin(x**2) # Create subplots fig, axs = plt.subplots(figsize=(7,4)) # Draw the plot axs.plot(x, y) # Show the plot plt.show() Output On executing the above code we will get the following output − Customizing the axes Data The Axes object contains most of the figure elements such as Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. These elements can be customized by adding labels, titles, legends, and annotations to the Axes enhances the clarity of visualizations. Example Here is a simple example that adds the labels, titles, legends to an Axes. import matplotlib.pyplot as plt import numpy as np # Sample Data x = np.linspace(0, 2 * np.pi, 400) y = np.sin(x**2) # Create subplots fig, axs = plt.subplots(figsize=(7,4)) # Draw the plot axs.plot(x, y, label=”Sin(x)”) # Add titles axs.set_title(”Sin Plot”) # Add X and Y labels axs.set_xlabel(”X-axis”) axs.set_ylabel(”Y-axis”) # Add legend axs.legend() # Show the plot plt.show() Output On executing the above code we will get the following output − Clearing the Axes To clear the contents of an axes, you can use the axes.cla() or axes.clear() method. Example Here is an example that show how you can clear the first axes in a subplot. import matplotlib.pyplot as plt import numpy as np # Sample data x = np.linspace(-1, 1, 10) y = np.exp(x) # Creating subplots fig, (axes1, axes2) = plt.subplots(1, 2, figsize=(7, 4), constrained_layout=True) # Plotting on the first axes axes1.plot(x, y, c=”red”) axes1.set_xlabel(“X-axis”) # Set label for X-axis axes1.set_ylabel(“Y-axis”) # Set label for Y-axis axes1.set_facecolor(”lightgreen”) # Setting background color axes1.annotate(”axes1”, (0.5, 0.5), transform=axes1.transAxes, ha=”center”, va=”center”, fontsize=18, color=”darkgrey”) # Adding a title to the second axes axes2.set_title(”Second axes”) axes2.annotate(”axes2”, (0.5, 0.5), transform=axes2.transAxes, ha=”center”, va=”center”, fontsize=18, color=”darkgrey”) # Clearing the first axes axes1.cla() # Adding a title to the figure fig.suptitle(”Clearing the Axes”) # Displaying the plot plt.show() Output On executing the above code you will get the following output − Print Page Previous Next Advertisements ”;

Matplotlib – Axis Ranges

Matplotlib – Axis Ranges ”; Previous Next What is Axis Range? Axis range in Matplotlib refers to the span of values displayed along the x-axis and y-axis in a plot. These ranges determine the visible data within the plot area and are defined by the minimum and maximum values displayed on each axis. Customizing axis ranges in Matplotlib allows for better control over the visible data within the plot by enabling the emphasis of specific ranges or patterns to enhance the visualization. The Key Points about Axis Ranges X-axis and Y-axis Ranges − Axis ranges can be adjusted independently for the x-axis and y-axis to display specific portions of the data. Setting Ranges − We can manually set the axis ranges using functions like plt.xlim() and plt.ylim() or their equivalent methods when working with an axis object ax.set_xlim() and ax.set_ylim(). Automatic Ranges − By default the Matplotlib library automatically calculates and sets the axis ranges based on the data provided. However manual adjustment allows focusing on specific data ranges or enhancing visualization. Use Cases for Axis Ranges Zooming In or Out − Adjusting axis ranges to focus on specific parts of the data by zooming in or out within the plot. Data Emphasis − Highlighting specific ranges of the data to emphasize patterns or trends. Avoiding Clutter − We can adjust the ranges of the plot axis, to prevent the overlapping of data point to improve the visualization of certain sections of the plot. Key Concepts in Axis Range The following are the key concepts of the axis range of the plot. Let’s see each of them in detail. X-Axis Range The x-range in axis range refers to the span of values displayed along the x-axis in a plot. It determines the minimum and maximum values visible on the horizontal axis by defining the range of data shown in that dimension. In Matplotlib library we can set the x-axis range using plt.xlim() or ax.set_xlim() to specify the limits for the x-axis. This allows us to control the displayed range of data along the x-axis. Controlling the x-range in axis ranges provides flexibility in visualizing specific segments of data along the x-axis by enabling better interpretation and analysis of the plotted information. Example using plt.xlim() In this example plt.xlim(1, 5) sets the x-axis limits from 1 to 5 by defining the x-range visible in the plot to cover data points between 1 and 5 along the x-axis. import matplotlib.pyplot as plt # Sample data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Creating a plot plt.plot(x, y) # Setting x-axis limits (x-range) plt.xlim(1, 5) # Set x-axis limits from 1 to 5 plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Plot with Custom X-axis Range”) plt.show() Output Example using the ax.set_xlim() Here”s an example demonstrating the use of ax.set_xlim() to set the x-axis limits when working with an axis object ax. import matplotlib.pyplot as plt # Sample data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Creating a figure and axis fig, ax = plt.subplots() # Plotting on the axis ax.plot(x, y) # Setting x-axis limits using axis object ax.set_xlim(0, 6) # Set x-axis limits from 0 to 6 # Labeling axes and adding title ax.set_xlabel(”X-axis”) ax.set_ylabel(”Y-axis”) ax.set_title(”Plot with Custom X-axis Limits”) plt.show() Output Y-Axis Range Setting the y-axis range or limits in Matplotlib allows us to specify the range of values displayed along the vertical y-axis of a plot. We can control the minimum and maximum values shown on the y-axis to focus on specific data ranges or patterns. The setting of range or limits of the y-axis in Matplotlib can be done using the plt.ylim() function or ax.set_ylim() method when working with an axis object ax. The range of values displayed along the vertical y-axis. Setting y-axis range is beneficial for focusing on specific data ranges, highlighting trends and ensuring the visualization emphasizes the relevant parts of the data along the y-axis. Example using plt.ylim() for Y-axis Range In this example the plt.ylim(0, 12) function sets the y-axis limits from 0 to 12 by specifying the range of values displayed on the y-axis. import matplotlib.pyplot as plt # Sample data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Creating a plot plt.plot(x, y) # Setting y-axis limits plt.ylim(0, 12) # Set y-axis limits from 0 to 12 plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Plot with Custom Y-axis Range”) plt.show() Output Example using ax.set_ylim() for Y-axis Range in Subplots When working with an axis object ax we can set the y-axis limits for a specific subplot as per our requirement. In this example ax.set_ylim(0, 20) sets the y-axis limits from 0 to 20 specifically for the subplot or axis ax. import matplotlib.pyplot as plt # Sample data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Creating subplots fig, ax = plt.subplots() # Plotting on the axis ax.plot(x, y) # Setting y-axis limits using axis object ax.set_ylim(0, 20) # Set y-axis limits from 0 to 12 ax.set_xlabel(”X-axis”) ax.set_ylabel(”Y-axis”) ax.set_title(”Plot with Custom Y-axis Range”) plt.show() Output Change the range of the X-axis and Y-axis This example changes the range of X and Y axes, we can use xlim() and ylim() methods. Example import numpy as np import matplotlib.pyplot as plt plt.rcParams[“figure.figsize”] = [7.50, 3.50] plt.rcParams[“figure.autolayout”] = True x = np.linspace(-15, 15, 100) y = np.sin(x) plt.plot(x, y) plt.xlim(-10, 10) plt.ylim(-1, 1) plt.show() Output Print Page Previous Next Advertisements ”;

Matplotlib – Annotations

Matplotlib – Annotations ”; Previous Next In Matplotlib library annotations refer to the capability of adding text or markers to specific locations on a plot to provide additional information or highlight particular features. Annotations allow users to label data points and indicate trends or add descriptions to different parts of a plot. Key Aspects of Annotations in Matplotlib The following are the key aspects of annotations in matplotlib library. Text Annotations Text annotations in data visualization are used to add explanatory or descriptive text to specific points, regions, or features within a plot. Annotations help in highlighting important information, providing context, or explaining trends and patterns within the visualized data. Marker Annotations Marker annotations in data visualization typically involve placing markers or symbols on specific points of interest within a plot to highlight or provide additional information about those points. These annotations can be textual or graphical and are commonly used to draw attention to significant data points, peaks, valleys, outliers or any crucial information in a visual representation. Callouts Callouts in data visualization refer to a specific type of annotation that uses visual elements like arrows, lines, or text to draw attention to a particular area or feature within a plot. They are often used to provide additional context or explanations about specific data points or regions of interest. The plt.annotate() function in Matplotlib library is used to add an annotation to a plot. It allows us to place a text annotation with optional arrows pointing to specific data points on the plot. Syntax The following is the syntax for the plt.annotate() function. plt.annotate(text, xy, xytext=None, xycoords=”data”, textcoords=”data”, arrowprops=None, annotation_clip=None, kwargs) Where, text (str) − The text of the annotation. xy (tuple or array) − The point (x, y) to annotate. xytext (tuple or array, optional) − The position (x, y) to place the text. If None defaults to `xy`. xycoords (str, Artist, or Transform, optional) − The coordinate system that `xy` is given in. Default is ”data”. textcoords (str, Artist, or Transform, optional) − The coordinate system that `xytext` is given in. Default is ”data”. arrowprops (dict, optional) − A dictionary of arrow properties. If not None an arrow is drawn from the annotation to the text. annotation_clip (bool or None, optional) − If True the text will only be drawn when the annotation point is within the axes. If None it will take the value from rcParams[“text.clip”]. kwargs (optional) − Additional keyword arguments that are passed to Text. Adding the annotation to the plot In this example we are using the plt.annotate() function to add an annotation with the text ”Peak” at the point (3, 5) on the plot. Example import matplotlib.pyplot as plt # Plotting data x = [1, 2, 3, 4, 5] y = [2, 3, 5, 7, 11] plt.plot(x, y, marker=”o”, linestyle=”-”, color=”blue”) # Adding annotation plt.annotate(”Peak”, xy=(3, 5), xytext=(3.5, 6), arrowprops=dict(facecolor=”black”, arrowstyle=”->”), fontsize=10) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Annotated Plot”) plt.grid(True) plt.show() Output Example Here this is another example of using the ‘plt.annotations’ function for adding the annotation to the image. import matplotlib.pyplot as plt # Sample data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Plotting data plt.plot(x, y, marker=”+”, linestyle=”-”) # Adding an annotation plt.annotate(”Point of Interest”, xy=(3, 6), xytext=(3.5, 7), arrowprops=dict(facecolor=”black”, arrowstyle=”->”)) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Annotated Plot”) plt.grid(True) plt.show() Output Insert statistical annotations (stars or p-values) In this example we are inserting the statistical annotations as stars r p-values. Example import numpy as np from matplotlib import pyplot as plt plt.rcParams[“figure.figsize”] = [7.00, 3.50] plt.rcParams[“figure.autolayout”] = True x = np.linspace(-1, 1, 5) y = np.linspace(-2, 2, 5) mean_x = np.mean(x) mean_y = np.mean(y) fig, ax = plt.subplots() ax.plot(x, y, linestyle=”-.”) ax.annotate(”*”, (mean_y, mean_y), xytext=(-.50, 1), arrowprops=dict(arrowstyle=”-|>”)) fig.autofmt_xdate() plt.show() Output Annotate Matplotlib Scatter Plots Here in this example we are adding the annotations to the scatter plot that we have plotted. Example # Import necessary libraries import matplotlib.pyplot as plt import numpy as np # Create data points to be plotted x = np.random.rand(30) y = np.random.rand(30) # Define the scatter plot using Matplotlib fig, ax = plt.subplots() ax.scatter(x, y) # Add annotations to specific data points using text or arrow annotations ax.annotate(”Outlier”, xy=(0.9, 0.9), xytext=(0.7, 0.7),arrowprops=dict(facecolor=”black”, shrink=0.05)) ax.annotate(”Important point”, xy=(0.5, 0.3), xytext=(0.3, 0.1),arrowprops=dict(facecolor=”red”, shrink=0.05)) ax.annotate(”Cluster of points”, xy=(0.2, 0.5), xytext=(0.05, 0.7),arrowprops=dict(facecolor=”green”, shrink=0.05)) # Adjust the annotation formatting as needed plt.title(”Annotated Scatter Plot”) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) # Show the scatter plot with annotations plt.show() Output Annotate the points on a scatter plot with automatically placed arrows In this example we are annotating the point on a scatter plot with automatically placed arrows. Example import numpy as np from matplotlib import pyplot as plt plt.rcParams[“figure.figsize”] = [7.00, 3.50] plt.rcParams[“figure.autolayout”] = True xpoints = np.linspace(1, 10, 25) ypoints = np.random.rand(25) labels = [“%.2f” % i for i in xpoints] plt.scatter(xpoints, ypoints, c=xpoints) for label, x, y in zip(labels, xpoints, ypoints): plt.annotate( label, xy=(x, y), xytext=(-20, 20), textcoords=”offset points”, ha=”right”, va=”bottom”, bbox=dict(boxstyle=”round,pad=0.5”, fc=”yellow”, alpha=0.5), arrowprops=dict(arrowstyle=”->”, connectionstyle=”arc3,rad=0”) ) plt.show() Output Print Page Previous Next Advertisements ”;

Matplotlib – Unit Handling

Matplotlib – Unit Handling ”; Previous Next What is Unit Handling? In Matplotlib library unit handling refers to the capability of the library to manage and interpret different types of units for plotting data accurately. Matplotlib allows users to specify and work with various units for defining and displaying data on plots whether they are related to length, time, angle or other physical quantities. Key Aspects of Unit Handling in Matplotlib The below are the key aspects of unit handling in matplotlib library. Support for Various Units Matplotlib supports multiple units such as pixels, inches, centimeters, points, fractions of the figure size and more. This flexibility allows users to define plot elements like positions, sizes and spacing using the unit of their choice. Conversion and Transformation Matplotlib handles unit conversions and transformations seamlessly. It enables automatic conversion between different units when plotting or specifying attributes such as size, location or dimensions. Unit-Aware Functions Many Matplotlib functions and methods are unit-aware which means they accept arguments or parameters in different units and internally manage the conversion for plotting purposes. Functions and Techniques for Unit Handling There are few techniques and functions available for unit handling. Automatic Conversion Matplotlib automatically handles unit conversion for plotting data. When using plot() function or other plotting functions the library converts data units to display units based on the chosen coordinate system. This automatic conversion simplifies the process of plotting data in Matplotlib by handling the conversion between different units without requiring explicit conversion steps from the user. Here”s an example demonstrating auto-conversion in unit handling. Example import matplotlib.pyplot as plt # Sample data in different units time_seconds = [1, 2, 3, 4, 5] # Time in seconds distance_meters = [2, 4, 6, 8, 10] # Distance in meters plt.plot(time_seconds, distance_meters) # Matplotlib handles unit conversion plt.xlabel(”Time (s)”) plt.ylabel(”Distance (m)”) plt.title(”Auto-Conversion of Units in Matplotlib”) plt.show() Output Axis Labeling In Axis labeling we use xlabel() and ylabel() functions to label the x-axis and y-axis respectively. These functions allow us in specifying units for the axis labels. We can adjust the labels accordingly to match the units of the data being plotted. This practice helps provide context and clarity to the plotted data for anyone viewing the graph. The below is an example demonstrating how to label axes with units using Matplotlib. Example import matplotlib.pyplot as plt # Sample data time = [0, 1, 2, 3, 4] # Time in seconds distance = [0, 10, 20, 15, 30] # Distance in meters # Creating a plot plt.plot(time, distance) # Labeling axes with units plt.xlabel(”Time (s)”) plt.ylabel(”Distance (m)”) plt.title(”Distance vs. Time”) plt.show() Output Custom Units For more explicit control set_units() methods for axes ax.xaxis.set_units() and ax.yaxis.set_units() can be used to explicitly set the units for the x-axis and y-axis. This custom axis unit handling ensures that the plot displays the data using specific units such as hours for time, kilometers for distance etc and labels the axes accordingly providing context and clarity to the visualization. Here”s an example demonstrating custom axis unit handling in Matplotlib. Example import matplotlib.pyplot as plt # Sample data time_hours = [1, 2, 3, 4, 5] # Time in hours distance_km = [50, 80, 110, 140, 170] # Distance in kilometers fig, ax = plt.subplots() # Plotting the data ax.plot(time_hours, distance_km) # Customizing x-axis and y-axis units ax.xaxis.set_units(”hours”) # Set x-axis units to hours ax.yaxis.set_units(”km”) # Set y-axis units to kilometers # Labeling axes with units ax.set_xlabel(”Time”) ax.set_ylabel(”Distance”) ax.set_title(”Distance over Time”) plt.show() Output Unit Conversion Functions like convert_xunits() and convert_yunits() within plt.gca() can convert data units to display units. Here is an example demonstrating unit conversion in unit handling in Matplotlib Example import matplotlib.pyplot as plt # Specify figure size in inches plt.figure(figsize=(6, 4)) # Width: 6 inches, Height: 4 inches # Set x-axis label with different units plt.xlabel(”Distance (cm)”) # Using centimeters as units # Plotting data with specific units x = [1, 2, 3, 4] y = [10, 15, 12, 18] plt.plot(x, y) plt.title(”Plot with Unit Handling”) plt.show() Output Use Cases for Unit Handling Consistency in Measurement − Ensuring consistent units across labels, annotations and plot elements for clarity. Dimension-Agnostic Plotting − Plotting data regardless of the unit type such as length, time etc. with Matplotlib handling conversions and scaling appropriately. Customization Flexibility − Allowing users to define plot attributes using their preferred units for better control over visualizations. Print Page Previous Next Advertisements ”;

Matplotlib – LaTeX Text Formatting in Annotations

Matplotlib – LaTeX Text Formatting in Annotations ”; Previous Next What is Text formatting in LaTex? In LaTeX text formatting in annotations within figures, graphs or plots such as those created. Matplotlib library can be accomplished using a subset of LaTeX commands within the annotation text. Annotations help add explanatory labels, descriptions or notes to elements within a graph. When working with tools like Matplotlib that support LaTeX for text rendering in annotations we can use a subset of LaTeX commands to format the text within these annotations. This allows for the incorporation of styled text, mathematical expressions and special formatting within annotations. LaTeX Formatting in Annotations Includes The below are the LaTex formatting in Annotations. Let’s see them one by one. Mathematical Expressions − The mathematical expressions are given as fractions, Greek letters, superscripts and subscripts using LaTeX math mode. Text Styling − The text styling includes bold, italics, underline or different font sizes using LaTeX commands like textbf{}, textit{}, underline{} and font size commands. Special Characters − Escaping special characters like dollar signs, percentage signs or underscores using LaTeX escape sequences. Alignment − Control over alignment, though limited, using begin{flushleft}…end{flushleft}, begin{center}…end{center}, begin{flushright}…end{flushright}. In the above we have gone through different styling formats available in LaTex, now let’s see the text formatting in Annotations using LaTex. LaTeX Text Formatting in Annotations The below are the various text formatting in Annotations using LaTex. Basic Text Formatting LaTeX commands for basic text formatting can be used in annotations. The following are some. Bold − To make text bold textbf{Bold Text} Italics − To make text italic textit{Italic Text} Underline − To add an underline to text underline{Underlined Text} Font Size − LaTeX provides different font size commands such as tiny, small, large, Large, huge, Huge Annotations with Bold text using LaTex Here in this example we are using the LaText text formatting in the Annotations for making the text to look bold on a plot. Example import matplotlib.pyplot as plt # Create a simple plot x = [1, 2, 3, 4] y = [2, 5, 7, 10] plt.plot(x, y, marker=”o”, linestyle=”-”) # Add an annotation with LaTeX text formatting plt.annotate(r”textbf{Max Value}”, xy=(x[y.index(max(y))], max(y)), xytext=(2.5, 8), arrowprops=dict(facecolor=”black”, shrink=0.05), fontsize=12, color=”blue”, bbox=dict(boxstyle=”round,pad=0.3”, edgecolor=”blue”, facecolor=”lightblue”)) # Set axis labels and title plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Example Plot with LaTeX Annotation”) # Show the plot plt.show() Output On executing the above code you will get the following output − Mathematical Notation In LaTeX text formatting within mathematical notation involves using commands and syntax within math mode to stylize text elements while expressing mathematical content. It allows for the integration of text formatting features within mathematical expressions or equations. Basic Text Formatting within Mathematical Notation The basic text formatting within the mathematical notations are as follows. Bold Text This text formatting renders the enclosed text in bold within a mathematical expression. mathbf{Bold Text} Italic Text The Italic text displays the enclosed text in italics within a mathematical expression. textit{Italic Text} Sans-serif Text This renders the enclosed text in sans-serif font style within math mode. textsf{Sans-serif Text} Typewriter Text This displays the enclosed text in a typewriter or monospaced font within math mode. texttt{Typewriter Text} Important points to remember Text formatting within mathematical notation can be achieved using text{} or specific formatting commands within math mode. Some formatting commands may not work in all math environments or may need additional packages or configurations. LaTeX offers a variety of text formatting options that can be applied within mathematical expressions to enhance the presentation of text-based content. By utilizing text formatting commands within mathematical notation LaTeX allows for the integration of styled text elements within mathematical expressions by aiding in the clarity and visual appeal of mathematical content. Subscripts and Superscripts In LaTeX subscripts and superscripts are used to position text or symbols below subscripts or above superscripts the baseline of a mathematical expression. They”re commonly employed to denote indices, exponents or special annotations within mathematical notation. Subscripts Subscripts are used to create a subscript in LaTeX we can use the underscore `_`. Superscripts Superscripts to create a superscript in LaTeX we can use the caret `^`. Subscripts and Superscripts usage in Annotation of a plot In this example we are using the subscripts and superscripts usage in annotations of a plot by using the LaTex. Example import matplotlib.pyplot as plt # Generating some data points x = [1, 2, 3, 4] y = [2, 5, 7, 10] plt.plot(x, y, ”o-”, label=”Data”) # Annotating a point with a subscript and a superscript plt.annotate(r”$mathrm{Point}_{mathrm{max}}^{(4, 10)}$”, xy=(x[y.index(max(y))], max(y)), xytext=(3, 8), arrowprops=dict(facecolor=”black”, arrowstyle=”->”), fontsize=12, color=”red”) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Example Plot with Annotation”) plt.legend() plt.show() Output On executing the above code you will get the following output − Important points to remember Subscripts and superscripts can be used independently or combined within LaTeX mathematical notation. They are crucial for denoting variables, indices, exponents and other related mathematical annotations. LaTeX automatically handles the positioning and sizing of subscripts and superscripts based on the context and surrounding elements within the mathematical expression. By using subscripts and superscripts in LaTeX we can precisely express mathematical formulas and notations, improving clarity and readability within mathematical content. Combining Text and Math Combining text and math in annotations using LaTeX involves embedding both regular text and mathematical expressions within annotations in a coherent and visually effective manner. Combining Text and Math using Latex on a plot Here in this example we are combining the text and math in

Matplotlib – What is LaTeX?

Matplotlib – What is LaTeX? ”; Previous Next LaTeX is a typesetting system widely used for producing scientific and technical documents, particularly in disciplines such as mathematics, physics, computer science, engineering and academic writing. It”s highly regarded for its superior typesetting of complex mathematical equations, scientific notations, and structured text formatting. Key Aspects of LaTeX The below are the key aspects of LaTeX. Markup Language LaTeX is a markup language, meaning it uses commands and tags to format text rather than WYSIWYG which is abbreviated as What You See Is What You Get editors. Users write plain text with embedded commands that specify the structure and formatting. High-Quality Typesetting LaTeX excels in producing professional-looking documents with precise typographical and typesetting features. It handles complex structures like mathematical formulas, tables, bibliographies and cross-references exceptionally well. Package System LaTeX offers a vast array of packages that extend its functionality for specific tasks or document types, providing templates, styles and additional features. Free and Open Source LaTeX is free to use and is supported by a strong open-source community by ensuring continuous development and a rich ecosystem of packages and resources. Components of LaTeX The LaTex of matplotlib library have the following components. Let’s see each of them in detail. Document Class The document class specifies the type of document being created and defines its overall structure, layout and formatting. It acts as a template that sets the style and behavior for the entire document. Different document classes are available to suit various types of documents such as articles, reports, books, presentations and more. Preamble In LaTeX the preamble is the section of the document that precedes the main content and the begin{document} command. It is where we define the document settings, load packages, set parameters and configure global settings that apply to the entire document. The preamble acts as a setup area where we prepare LaTeX for processing the main body of the document. Document Body The document body in LaTeX is the main section where the content of our document resides. It starts after the preamble and the begin{document} command and continues until the end{document} command. This section includes the actual text, sections, subsections, equations, figures, tables and any other elements that constitute the core content of the document. Advantages of LaTeX The following are the advantages of LaTex. Quality Typesetting − Produces high-quality output, especially for scientific and technical documents. Cross-Referencing − Simplifies referencing and cross-referencing of equations, figures, tables, and sections. Version Control − Facilitates version control and collaboration through plain text-based files. Customization − Allows extensive customization of document styles, layouts and formatting. Disadvantages of LaTeX Learning Curve − Requires learning its syntax and commands which can be daunting for beginners. Limited WYSIWYG − Lack of immediate visual feedback (WYSIWYG) might be challenging for some users accustomed to graphical editors. Usage of LaTeX Academic Writing − Academic papers, theses, dissertations Scientific − Scientific reports, articles, and journals Technical Documents − Technical documentation, manuals Presentations − Presentations using tools like Beamer Basic document structure of the LaTex Syntax A basic LaTeX document structure includes − documentclass{article} begin{document} section{Introduction} This is a simple LaTeX document. subsection{Subsection} Some text in a subsection. end{document} The above code defines a basic article document with a hierarchical structure comprising a section and a subsection. LaTeX is a powerful tool for producing structured, high-quality documents especially in technical and academic fields. While it has a learning curve its ability to handle complex mathematical notations and produce professional-looking documents makes it a preferred choice for many researchers, academics and professionals. Write our own LaTeX preamble To write our own LaTeX preamble in Matplotlib we can use this example as reference. Example 1 import numpy as np from matplotlib import pyplot as plt plt.rcParams[“figure.figsize”] = [7.50, 3.50] plt.rcParams[“figure.autolayout”] = True x = np.linspace(-10, 10, 100) y = np.exp(x) plt.plot(x, y, color=”red”, label=”$y=e^{x}$”) plt.legend(loc=”upper right”) plt.show() Output On executing the above code you will get the following output − Latex formula in the legend of a plot using Matplotlib inside a .py file In this example we are using the Latex formula in the legend of a plot inside a .py file. Example 2 import numpy as np import matplotlib.pyplot as plt plt.rcParams[“figure.figsize”] = [7.50, 3.50] plt.rcParams[“figure.autolayout”] = True x = np.linspace(1, 10, 1000) y = np.sin(x) plt.plot(x, y, label=r”$sin (x)$”, c=”red”, lw=2) plt.legend() plt.show() Output On executing the above code you will get the following output − Put a little more complex equation in the label, for example, label=r”αiπ+1=0” Now, look at the legend at the top-right corner of the plot. Print Page Previous Next Advertisements ”;

Matplotlib – Image Masking

Matplotlib – Image Masking ”; Previous Next In Matplotlib library image masking involves selectively displaying parts of an image based on a specified mask which is essentially a binary image defining regions to be shown or hidden. It allows us to apply a filter or condition to reveal or hide specific portions of an image. Process of Image Masking The below are the process steps for performing Image Masking. Create a Mask Define the criteria or pattern to create the mask. It can be based on colors, shapes, gradients or specific pixel values. Apply the Mask Use the mask to modify the transparency or visibility of the corresponding pixels in the original image. Pixels that correspond to areas defined in the mask as “masked” are usually hidden or made transparent while others remain visible. Overlay or Blend Overlay or blend the masked image with another image or a background revealing only the unmasked portions. The masked image can be superimposed on another image to combine and display the visible areas. Types of Image Masks The below are the types of Image masks. Binary Masks Consist of black and white pixels where white represents visible areas and black represents masked areas. Grayscale Masks Use various shades of gray to define levels of transparency or partial visibility. Tools and Techniques for Image Masking We can use the different tools and techniques for Image masking. Manual Masking Tools like Photoshop or GIMP allow users to manually create and edit masks using selection tools, brushes or layer masks. Programmatic Masking In programming languages like Python with libraries such as OpenCV or PIL (Pillow) we can create masks using algorithms based on color thresholds, contours or specific image features. Key Points Image masking in Matplotlib involves creating a mask array with the same dimensions as the image where specific regions are marked to hide (masked) or reveal (unmasked) portions of the image. Masking arrays consist of boolean or numerical values where True or non-zero values indicate the regions to be displayed, and False or zero values indicate the regions to be hidden. Masking allows for selective visualization or manipulation of specific parts of an image based on specified conditions or criteria. Masking the particular region of the Image Let”s say we have an image and want to mask a particular region displaying only a portion of the image based on certain criteria. Example import matplotlib.pyplot as plt import numpy as np # Create a sample image (random pixels) image = np.random.rand(100, 100) # Create a mask to hide certain parts of the image mask = np.zeros_like(image) mask[30:70, 30:70] = 1 # Masking a square region # Apply the mask to the image masked_image = np.ma.masked_array(image, mask=mask) # Display the original and masked images plt.figure(figsize=(8, 4)) plt.subplot(1, 2, 1) plt.imshow(image, cmap=”gray”) plt.title(”Original Image”) plt.axis(”off”) plt.subplot(1, 2, 2) plt.imshow(masked_image, cmap=”gray”) plt.title(”Masked Image”) plt.axis(”off”) plt.show() Output Applying mask to an Image Here this is another of masking an image using the matplotlib library. Example import matplotlib.pyplot as plt import numpy as np # Create a sample image image_size = 100 img = np.zeros((image_size, image_size, 3), dtype=np.uint8) img[:, :image_size // 2] = [255, 0, 0] # Set the left half to blue # Create a binary mask mask = np.zeros((image_size, image_size), dtype=np.uint8) mask[:, image_size // 4:] = 1 # Set the right quarter to 1 # Apply the mask to the image masked_img = img * mask[:, :, np.newaxis] # Display the original image, mask, and the masked image plt.figure(figsize=(12, 4)) plt.subplot(131) plt.imshow(img) plt.title(”Original Image”) plt.axis(”off”) plt.subplot(132) plt.imshow(mask, cmap=”gray”) plt.title(”Mask”) plt.axis(”off”) plt.subplot(133) plt.imshow(masked_img) plt.title(”Masked Image”) plt.axis(”off”) plt.show() Output Print Page Previous Next Advertisements ”;