Matplotlib – Pick Event ”; Previous Next In computer programming, a click event refers to an occurrence where a user interacts with an element on the screen, typically by selecting or clicking on it. The event is triggered when the user”s input device, such as a mouse or touchscreen, interacts with an object in the graphical representation. Pick Event in Matplotlib A pick event in matplotlib occurs when a user selects a location on the canvas close to an artist that has been designated as pickable using Artist.set_picker. This event provides a way to interactively respond to user actions such as clicking on points, rectangles, or text in a plot. Enabling the Pick Event Enabling the picking ability of an object can be done by setting the “picker” property of an artist such as Line2D, Text, Patch, Polygon, AxesImage, etc. This property determines whether the artist can trigger a pick event based on user interactions. The options available for the “picker” property are − None − Picking is disabled, which is the default behavior. bool − If True, picking is enabled, and the artist fires a pick event if the mouse event is over it. function − A user-supplied function that determines whether the artist is hit by the mouse event. The function should return hit, props = picker(artist, mouseevent). After enabling an artist for picking, you need to connect to the figure canvas using the fig.canvas.mpl_connect(”pick_event”, callback_function) method to receive pick callbacks on mouse press events. Picking the Points, Rectangles, and Text It is possible to enable the picking of specific elements like points, rectangles, and text within a plot. This allows users to click on these elements and trigger custom actions. Example The following example demonstrates picking points, rectangles, and text in a plot to get the properties of those picked objects. import matplotlib.pyplot as plt import numpy as np from numpy.random import rand from matplotlib.lines import Line2D from matplotlib.patches import Rectangle from matplotlib.text import Text # Fixing random state for reproducibility np.random.seed(19680801) fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(7, 7)) ax1.set_title(”click on points, rectangles or text”, picker=True) ax1.set_xlabel(”xlabel”, picker=True, bbox=dict(facecolor=”green”)) ax1.set_ylabel(”ylabel”, picker=True, bbox=dict(facecolor=”red”)) line, = ax1.plot(rand(100), ”o”, picker=True, pickradius=5) # Pick the rectangle. ax2.bar(range(10), rand(10), picker=True) # Make the xtick labels pickable. for label in ax2.get_xticklabels(): label.set_picker(True) def onpick(event): if isinstance(event.artist, Line2D): thisline = event.artist xdata = thisline.get_xdata() ydata = thisline.get_ydata() ind = event.ind print(”onpick line:”, np.column_stack([xdata[ind], ydata[ind]])) elif isinstance(event.artist, Rectangle): patch = event.artist print(”onpick patch:”, patch.get_path()) elif isinstance(event.artist, Text): text = event.artist print(”onpick text:”, text.get_text()) fig.canvas.mpl_connect(”pick_event”, onpick) plt.show() Output On executing the above program you will get the following figure, and click on any points, rectangles, or text to observe the working of this example − Following are the properties observed on console window − onpick line: [[45. 0.63297416]] onpick text: xlabel onpick text: ylabel onpick patch: Path(array([[0., 0.], [1., 0.], [1., 1.], [0., 1.], [0., 0.]]), array([ 1, 2, 2, 2, 79], dtype=uint8)) onpick patch: Path(array([[0., 0.], [1., 0.], [1., 1.], [0., 1.], [0., 0.]]), array([ 1, 2, 2, 2, 79], dtype=uint8)) onpick line: [[85. 0.93665595]] onpick text: click on points, rectangles or text onpick text: 4 Watch the video below to observe how this pick event feature works here. Picking on a Scatter Plot Picking on a scatter plot involves selecting individual points represented by markers. Scatter plots are commonly used to visualize relationships between two variables. Enabling picking on a scatter plot allows users to interactively identify and respond to specific data points. Example This example demonstrates picking on a scatter plot where scatter points are backed by a PathCollection. from numpy.random import rand import matplotlib.pyplot as plt # Generate sample data x, y, c, s = rand(4, 100) # Define a function to handle pick events on the scatter plot def onpick3(event): ind = event.ind print(”onpick3 scatter:”, ind, x[ind], y[ind]) # Create a Matplotlib figure and axis fig, ax = plt.subplots(figsize=(7, 4)) ax.set_title(”Click on the points”) # Create a scatter plot ax.scatter(x, y, 100*s, c, picker=True) # Connect the pick event handler to the figure canvas fig.canvas.mpl_connect(”pick_event”, onpick3) plt.show() Output On executing the above program you will get the following figure, and click on any points, rectangles, or text to observe the working of this example − onpick scatter: [25] [0.11699828] [0.53441235] onpick scatter: [27 44] [0.24286321 0.24281114] [0.37273147 0.3410762 ] onpick scatter: [86] [0.40636809] [0.44143683] onpick scatter: [60] [0.38819555] [0.47496597] onpick scatter: [51] [0.63094438] [0.57754482] onpick scatter: [71] [0.27925334] [0.01716168] onpick scatter: [72 94] [0.859042 0.86511669] [0.19949375 0.16885001] onpick scatter: [37] [0.95150989] [0.11653306] Watch the video below to observe how this pick event feature works here. Images Picking Images that are plotted using Axes.imshow can also be made pickable. Example In this example, picking is demonstrated on images plotted using Axes.imshow() method. import numpy as np import matplotlib.pyplot as plt from matplotlib.image import AxesImage # Create a Matplotlib figure and axis fig, ax = plt.subplots(figsize=(7, 4)) # Display the images ax.imshow(np.random.rand(10, 5), extent=(1, 2, 1, 2), picker=True) ax.imshow(np.random.rand(5, 10), extent=(3, 4, 1, 2), picker=True) ax.imshow(np.random.rand(20, 25), extent=(1, 2, 3, 4), picker=True) ax.imshow(np.random.rand(30, 12), extent=(3, 4, 3, 4), picker=True) ax.set(xlim=(0, 5), ylim=(0, 5)) # Define a function to handle pick events def onpick(event): artist = event.artist if isinstance(artist, AxesImage): im = artist A = im.get_array() print(”onpick image”, A.shape) # Connect the pick event handler to the figure canvas fig.canvas.mpl_connect(”pick_event”, onpick) plt.show() Output On executing the above program you will get the following figure, and click on any points, rectangles, or text to observe the working of this example − onpick image (20, 25) onpick image (30, 12) onpick image (10,
Category: matplotlib
Matplotlib – Findobj Demo
Matplotlib – Findobj Demo ”; Previous Next In Matplotlib, the findobj is a method used for locating and manipulating graphical objects within a figure. Its primary purpose is to provide a flexible and convenient way to search for specific artist instances and modify their properties within a plot. This method is available in both the interfaces such as pyplot.findobj() and axes.Axes.findobj() (pyplot and Object-oriented interfaces). All Artist objects in Matplotlib inherit this method, allowing for recursive searches within their hierarchy. The findobj method takes a matching criterion and optionally includes the object itself in the search. In this tutorial, we will explore the fundamental concepts behind the findobj method in Matplotlib. Finding object The findobj() method can be used to locate specific types of objects within a plot. For example, users can search for Line2D instances to identify plotted lines within the current Axes. Example The following example creates two sets of line plots using the plot() method then you can use the findobj() method to find out the Line2D instance corresponding to the sinusoidal line. import matplotlib.pyplot as plt from matplotlib.lines import Line2D import numpy as np # Generate data t = np.arange(0, 4, 0.1) F1 = np.sin(2 * t) F2 = np.exp(-t*4) # Plot two lines fig, ax = plt.subplots(figsize=(7, 4)) line1, = ax.plot(t, F1, ”green”, label=”Sinusoidal”) line2, = ax.plot(t, F2, ”b–”, label=”Exponential Decay”) # Find the Line object corresponding to the sinusoidal line line_handle = plt.gca().findobj(Line2D)[0] # Display the results print(“Found Line2D instance:”, line_handle) # Display the modified plot plt.legend() plt.show() Output On executing the above code we will get the following output − Found Line2D instance: Line2D(Sinusoidal) Modifying Objects Once an object is located/identified using the findobj() method, users can modify its properties to achieve the desired visualization. This includes changing attributes such as color, linestyle, text content, and more. Example 1 Here is an example that creates a plot with three Text objects containing different text content. The Axes.findobj() method is used to locate a Text object with specific text content (”tutorialspoint”). Once found, the text content is modified to ”Tutorialspoint :)” and its color is changed to green. import matplotlib.pyplot as plt from matplotlib.text import Text # Create a plot with a text object fig, ax = plt.subplots() ax.text(.4, .5, s=”tutorialspoint”) ax.text(.1, .1, s=”Python”) ax.text(.8, .8, s=”Matplotlib”) # Find the Text object with the text ”tutorialspoint” text_handle = ax.findobj( lambda artist: isinstance(artist, Text) and artist.get_text() == ”tutorialspoint”)[0] # Modify the text text_handle.set_text(”Tutorialspoint :)”) text_handle.set_color(”green”) plt.show() Output On executing the above code we will get the following output − Users can also define custom matching functions to filter objects based on specific criteria. This allows for more complex searches and enables advanced manipulation of graphical objects. Example 2 Here is another example that demonstrates how to use of a custom matching function to modify objects using the Figure.findobj() method. import matplotlib.pyplot as plt import matplotlib.text as text import numpy as np # Generate data t = np.arange(0, 4, 0.1) F1 = np.sin(2 * t) F2 = np.exp(-t * 4) # Plot two lines fig, ax = plt.subplots(figsize=(7, 4)) line1, = ax.plot(t, F1, ”red”, label=”Sinusoidal”) line2, = ax.plot(t, F2, ”k–”, label=”Exponential Decay”) plt.grid(False) plt.xlabel(”x label”) plt.ylabel(”y label”) plt.title(”Modifying the Objects”) # Define a custom function for matching def myfunc(x): return hasattr(x, ”set_color”) and not hasattr(x, ”set_facecolor”) # Modify objects based on the custom function for o in fig.findobj(myfunc): o.set_color(”green”) # Display the modified plot plt.show() Output On executing the above code we will get the following output − Print Page Previous Next Advertisements ”;
Matplotlib – Sankey Class
Matplotlib – Sankey Class ”; Previous Next Sankey Class in matplotlib is used to create Sankey diagrams, Before diving into the Sankey Class, it”s essential to understand the basics of Sankey diagrams. A Sankey diagram is a powerful visualization tool that represents the flow of resources, energy, or information between different entities or processes. It uses arrows of varying widths to depict the quantity of flow, with the width being proportional to the quantity being represented. See the below image for the reference of a simple Sankey Diagram Key Components of a Sankey Diagram Nodes − Entities or processes between which the flow occurs. Flows − Arrows connecting nodes, representing the quantity of the flow. Labels − Descriptions associated with nodes or flows. Sankey Class in Matplotlib In Matplotlib, the Sankey() class provides a convenient way to create these diagrams. Below is the syntax of the class − Syntax class matplotlib.sankey.Sankey(ax=None, scale=1.0, unit=””, format=”%G”, gap=0.25, radius=0.1, shoulder=0.03, offset=0.15, head_angle=100, margin=0.4, tolerance=1e-06, **kwargs) Following are the steps to create a Sankey diagram using matplotlib Sankey Class − Creating a Sankey Object − This can be done by using the Sankey() class which initializes an instance of the Sankey class, which will be used to build the diagram. Adding the Flows and Labels − The Sankey.add() method is used to specify the flows and labels. Finish and Display − The Sankey.finish() method finalizes the diagram, and plt.show() displays it. Drawing a Basic Sankey Diagram Now, let”s build a simple Sankey diagram with The default settings. The below example creates a diagram of one input and output flow. The flows are specified with the flows argument, while labels are provided using labels argument. Example 1 Here is the example that crates the Sankey diagram with one input and output flows. import matplotlib.pyplot as plt from matplotlib.sankey import Sankey sankey = Sankey() sankey.add(flows=[1, -1], labels=[”input”, ”output”]) plt.title(“Sankey Diagram”) sankey.finish() plt.show() Output On executing the above program, will generate the following Sankey diagram − Example 2 Another example demonstrates how to create a simple diagram by implicitly calling the Sankey.add() method and by appending finish() to the call to the class. import matplotlib.pyplot as plt from matplotlib.sankey import Sankey Sankey(flows=[0.25, 0.15, 0.60, -0.20, -0.15, -0.05, -0.50, -0.10], labels=[””, ””, ””, ”First”, ”Second”, ”Third”, ”Fourth”, ”Fifth”], orientations=[-1, 1, 0, 1, 1, 1, 0, -1]).finish() plt.title(“The default settings produce a diagram like this.”) plt.show() Output On executing the above program, will generate the following Sankey diagram − Customized Sankey Diagram The Matplotlib Sankey class provides more customization options, including connecting multiple Sankey diagrams together, placing a label in the middle of the diagram, implicitly passing keyword arguments to PathPatch(), changing the angle of the arrowheads, changing the appearance of the patch and the labels after the figure is created, and more. Example Here is an example that creates a complex customized Sankey Diagram using matplotlib sankey() class. import matplotlib.pyplot as plt from matplotlib.sankey import Sankey # Create a subplot fig = plt.figure() ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[], title=”Customized Sankey Diagram with Two Systems”) # Create a Sankey diagram sankey = Sankey(ax=ax, scale=0.01, offset=0.2, format=”%.0f”, unit=”%”) # Add flows and labels for the first system sankey.add(flows=[25, 0, 60, -10, -20, -5, -15, -10, -40], label=”one”, labels=[””, ””, ””, ”First”, ”Second”, ”Third”, ”Fourth”,”Fifth”, ”Hurray!”], orientations=[-1, 1, 0, 1, 1, 1, -1, -1, 0], pathlengths=[0.25, 0.25, 0.25, 0.25, 0.25, 0.6, 0.25, 0.25, 0.25], patchlabel=”WidgetnA”) # Add flows and labels for the second system, connected to the first sankey.add(flows=[-25, 15, 10], label=”two”, orientations=[-1, -1, -1], prior=0, connect=(0, 0)) # Finish the Sankey diagram and apply customizations diagrams = sankey.finish() diagrams[-1].patch.set_hatch(”/”) diagrams[0].texts[-1].set_color(”r”) diagrams[0].text.set_fontweight(”bold”) # Display the diagram plt.legend() plt.show() Output On executing the above program, will generate the following Sankey diagram − Print Page Previous Next Advertisements ”;
Matplotlib – Looking Glass
Matplotlib – Looking Glass ”; Previous Next A looking glass is a term often refers to an object with a reflective surface, such as a mirror, through which one can observe their own reflection or the surrounding environment. In terms of the graphical user interfaces, the term “looking glass” is sometimes used to describe a feature that provides a detailed view or insight into a specific aspect of a system or application. Looking Glass in Matplotlib In the context of Matplotlib, looking glass is a GUI application or example that implements an interactive circular window that reveals or hides portions of a Matplotlib plot. This looking glass example uses the Matplotlib”s patches module to create a interactive circular window. With this interactive nature allows users to explore the underlying data dynamically. This tutorial demonstrates how to create an interactive circular window, which is similar to a looking glass, that can be moved to reveal or hide portions of a plot beneath it. Defining and Visualizing initial plot Start by defining a predefined looking glass using the patches.Circle() class object. Following is the set up for the Initial plot appearance − import matplotlib.pyplot as plt import numpy as np import matplotlib.patches as patches np.random.seed(19680801) x, y = np.random.rand(2, 200) fig, ax = plt.subplots(figsize=(7, 4)) circle_= patches.Circle((0.5, 0.5), 0.25, alpha=0.8, fc=”yellow”) ax.add_patch(circle_) ax.plot(x, y, alpha=0.2) line, = ax.plot(x, y, alpha=1.0, clip_path=circle_) ax.set_title(“Left click and drag to move looking glass”) Implementing the Looking Glass Interaction Let’s see the implementation of the EventHandler class used for creating the interactive looking glass. This class captures the mouse events, allowing users to click, drag, and reposition the looking glass. class EventHandler: def __init__(self): # Connect event handlers to the figure canvas fig.canvas.mpl_connect(”button_press_event”, self.on_press) fig.canvas.mpl_connect(”button_release_event”, self.on_release) fig.canvas.mpl_connect(”motion_notify_event”, self.on_move) # Initialize the center coordinates of the circular window self.x0, self.y0 = circle_.center self.pressevent = None def on_press(self, event): # Check if the event occurred inside the plot area if event.inaxes != ax: return # Check if the click is inside the circular window if not circle_.contains(event)[0]: return # Store the press event self.pressevent = event def on_release(self, event): # Reset the press event and update the center coordinates self.pressevent = None self.x0, self.y0 = circle_.center def on_move(self, event): # Check if a press event has occurred and if the mouse is still inside the plot if self.pressevent is None or event.inaxes != self.pressevent.inaxes: return # Calculate the change in coordinates dx = event.xdata – self.pressevent.xdata dy = event.ydata – self.pressevent.ydata # Update the center coordinates of the circle_ular window circle_.center = self.x0 + dx, self.y0 + dy # Update the clip path and redraw the plot line.set_clip_path(circle_) fig.canvas.draw() Running the implementation Create an instance of the EventHandler class to create the looking glass on a plot. handler = EventHandler() Example Let’s see the complete code of the Matplotlib Looking Glass example. import matplotlib.pyplot as plt import numpy as np import matplotlib.patches as patches np.random.seed(19680801) # Generate random data for plot x, y = np.random.rand(2, 200) # Create a Matplotlib figure and axis fig, ax = plt.subplots(figsize=(7, 4)) # Create a circular window (looking glass) and add it to the plot circle_= patches.Circle((0.5, 0.5), 0.25, alpha=0.8, fc=”yellow”) ax.add_patch(circle_) # Plot the random data with transparency ax.plot(x, y, alpha=0.2) # Plot the same data again, but clip it to the circular window line, = ax.plot(x, y, alpha=1.0, clip_path=circle_) # Set the plot title ax.set_title(“Left click and drag to move looking glass”) class EventHandler: def __init__(self): # Connect event handlers to the figure canvas fig.canvas.mpl_connect(”button_press_event”, self.on_press) fig.canvas.mpl_connect(”button_release_event”, self.on_release) fig.canvas.mpl_connect(”motion_notify_event”, self.on_move) # Initialize the center coordinates of the circular window self.x0, self.y0 = circle_.center self.pressevent = None def on_press(self, event): # Check if the event occurred inside the plot area if event.inaxes != ax: return # Check if the click is inside the circular window if not circle_.contains(event)[0]: return # Store the press event self.pressevent = event def on_release(self, event): # Reset the press event and update the center coordinates self.pressevent = None self.x0, self.y0 = circle_.center def on_move(self, event): # Check if a press event has occurred and if the mouse is still inside the plot if self.pressevent is None or event.inaxes != self.pressevent.inaxes: return # Calculate the change in coordinates dx = event.xdata – self.pressevent.xdata dy = event.ydata – self.pressevent.ydata # Update the center coordinates of the circle_ular window circle_.center = self.x0 + dx, self.y0 + dy # Update the clip path and redraw the plot line.set_clip_path(circle_) fig.canvas.draw() # Create an instance of the EventHandler class handler = EventHandler() # Display the plot plt.show() On executing the above program you will get the following figure left click on mouse and drag the looking glass to observe the working of this example − Watch the video below to observe the works of this example. Print Page Previous Next Advertisements ”;
Matplotlib – Multiplots
Matplotlib – Multiplots ”; Previous Next In this chapter, we will learn how to create multiple subplots on same canvas. The subplot() function returns the axes object at a given grid position. The Call signature of this function is − plt.subplot(subplot(nrows, ncols, index) In the current figure, the function creates and returns an Axes object, at position index of a grid of nrows by ncolsaxes. Indexes go from 1 to nrows * ncols, incrementing in row-major order.Ifnrows, ncols and index are all less than 10. The indexes can also be given as single, concatenated, threedigitnumber. For example, subplot(2, 3, 3) and subplot(233) both create an Axes at the top right corner of the current figure, occupying half of the figure height and a third of the figure width. Creating a subplot will delete any pre-existing subplot that overlaps with it beyond sharing a boundary. import matplotlib.pyplot as plt # plot a line, implicitly creating a subplot(111) plt.plot([1,2,3]) # now create a subplot which represents the top plot of a grid with 2 rows and 1 column. #Since this subplot will overlap the first, the plot (and its axes) previously created, will be removed plt.subplot(211) plt.plot(range(12)) plt.subplot(212, facecolor=”y”) # creates 2nd subplot with yellow background plt.plot(range(12)) The above line of code generates the following output − The add_subplot() function of the figure class will not overwrite the existing plot − import matplotlib.pyplot as plt fig = plt.figure() ax1 = fig.add_subplot(111) ax1.plot([1,2,3]) ax2 = fig.add_subplot(221, facecolor=”y”) ax2.plot([1,2,3]) When the above line of code is executed, it generates the following output − You can add an insert plot in the same figure by adding another axes object in the same figure canvas. import matplotlib.pyplot as plt import numpy as np import math x = np.arange(0, math.pi*2, 0.05) fig=plt.figure() axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes axes2 = fig.add_axes([0.55, 0.55, 0.3, 0.3]) # inset axes y = np.sin(x) axes1.plot(x, y, ”b”) axes2.plot(x,np.cos(x),”r”) axes1.set_title(”sine”) axes2.set_title(“cosine”) plt.show() Upon execution of the above line of code, the following output is generated − Print Page Previous Next Advertisements ”;
Matplotlib – AGG filter
Matplotlib – AGG filter ”; Previous Next An AGG filter, which stands for “Aggregate Filter”, is used to sort through large amounts of data and only show the information that meets certain conditions. Imagine you have a big box of toys, and you only want to see the red ones. The AGG filter would help you quickly find and pick out all the red toys from the box while ignoring the others − AGG filter in Matplotlib In Matplotlib, an AGG filter, or Anti-Grain Geometry filter, is used to apply certain transformations to graphical elements, such as lines, markers, or text, before they are displayed on a plot. The AGG filter allows us to modify the appearance of elements in a plot, such as adjusting their transparency, blurring them, or applying other visual effects. You can use the “FigureCanvasAgg()” function to create an AGG filter in Matplotlib. This function creates a canvas with the AGG filter, allowing you to show plots and images with improved quality and clarity. Image Smoothing with AGG Filter In Matplotlib, image smoothing with the AGG filter is a technique used to blur or soften an image to reduce noise. The AGG filter is one of the options available for image smoothing, and it applies a mathematical algorithm to the image pixels, averaging neighboring pixels to create a smoother appearance. This process helps to remove uneven edges and create a more visually appealing image. Example In the following example, we perform image smoothing using the AGG filter. We begin by generating a random noisy image and then apply Gaussian smoothing using the gaussian_filter() function. Afterward, we create a Matplotlib figure with two subplots to display the original and smoothed images side by side − import matplotlib.pyplot as plt from matplotlib.backends.backend_agg import FigureCanvasAgg import numpy as np from scipy.ndimage import gaussian_filter # Generating random noisy image np.random.seed(0) image = np.random.rand(100, 100) # Applying Gaussian smoothing to the image smoothed_image = gaussian_filter(image, sigma=2) # Creating a figure and plot the original and smoothed images fig, axs = plt.subplots(1, 2, figsize=(10, 5)) axs[0].imshow(image, cmap=”gray”) axs[0].set_title(”Original Image”) axs[1].imshow(smoothed_image, cmap=”gray”) axs[1].set_title(”Smoothed Image (AGG Filter)”) # Hiding the axes for ax in axs: ax.axis(”off”) # Saving the figure as an image file canvas = FigureCanvasAgg(fig) canvas.print_png(”smoothed_image.png”) plt.show() Output Following is the output of the above code − Sharpening Image with AGG Filter In Matplotlib, sharpening an image with the AGG filter enhances the clarity and detail in an image by increasing the contrast along edges. It involves convolving the image with a sharpening kernel, which generally has positive values at the center surrounded by negative values. Example In here, we perform image sharpening using the AGG filter. We start by loading an image, then apply a sharpening filter to enhance the image”s edges. This involves defining a sharpening kernel and convolving it with the image using the scipy.ndimage.convolve() function. Finally we display the image − import matplotlib.pyplot as plt from matplotlib.backends.backend_agg import FigureCanvasAgg import numpy as np from scipy.ndimage import convolve # Loading an example image image = plt.imread(”sun.jpg”) # Converting to grayscale if image has multiple channels if len(image.shape) > 2: image = image.mean(axis=2) # Defining a sharpening kernel kernel = np.array([[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]]) # Applying the kernel to the image sharpened_image = np.clip(convolve(image, kernel, mode=”constant”, cval=0.0), 0, 1) # Creating a figure and plot the original and sharpened images fig, axs = plt.subplots(1, 2, figsize=(10, 5)) axs[0].imshow(image, cmap=”gray”) axs[0].set_title(”Original Image”) axs[1].imshow(sharpened_image, cmap=”gray”) axs[1].set_title(”Sharpened Image (AGG Filter)”) # Hiding the axes for ax in axs: ax.axis(”off”) # Saving the figure as an image file canvas = FigureCanvasAgg(fig) canvas.print_png(”sharpened_image.png”) plt.show() Output On executing the above code we will get the following output − Embossing Image with AGG Filter In Matplotlib, embossing an image with the AGG filter emphasizes the edges in an image, giving it a three-dimensional appearance by enhancing the contrast between neighboring pixels. It achieves this effect by convolving the image with an embossing kernel, which generally includes negative and positive values. Embossed images often have a raised or recessed appearance, simulating the effect of stamping or carving. Example In the example below, we use AGG filter to emboss an image. We start by loading an example image, then define an embossing kernel, a specific matrix designed to emphasize edges. Applying this kernel to the image using convolution generates the embossed image − import matplotlib.pyplot as plt from matplotlib.backends.backend_agg import FigureCanvasAgg import numpy as np from scipy.ndimage import convolve # Loading an example image image = plt.imread(”sun.jpg”) # Converting to grayscale if image has multiple channels if len(image.shape) > 2: image = image.mean(axis=2) # Defining an embossing kernel kernel = np.array([[-2, -1, 0], [-1, 1, 1], [0, 1, 2]]) # Applying the kernel to the image embossed_image = np.clip(convolve(image, kernel, mode=”constant”, cval=0.0), 0, 1) # Creating a figure and plot the original and embossed images fig, axs = plt.subplots(1, 2, figsize=(10, 5)) axs[0].imshow(image, cmap=”gray”) axs[0].set_title(”Original Image”) axs[1].imshow(embossed_image, cmap=”gray”) axs[1].set_title(”Embossed Image (AGG Filter)”) # Hiding the axes for ax in axs: ax.axis(”off”) # Saving the figure as an image file canvas = FigureCanvasAgg(fig) canvas.print_png(”embossed_image.png”) plt.show() Output After executing the above code, we get the following output − Print Page Previous Next Advertisements ”;
Matplotlib – Subplot Titles
Matplotlib – Subplot Titles ”; Previous Next What is Subplot Title? Subplot titles in Matplotlib refer to the individual titles assigned to each subplot within a larger figure. When we have multiple subplots arranged in a grid such as a matrix of plots it”s often beneficial to add titles to each subplot to provide context or describe the content of that specific subplot. Setting subplot titles is a useful practice when creating multiple visualizations within a single figure by enhancing the readability and comprehension of our overall plots. We have the method namely set_title() for setting the title of the subplot. By utilizing set_title() we can add descriptive titles to individual subplots within a figure allowing for better organization and comprehension of complex visualizations. Purpose of Subplot title Provide Context − Subplot titles offer descriptive information about the content of each subplot within a larger figure aiding in better understanding the visualizations. Differentiate Subplots − Titles help distinguish between multiple plots by allowing viewers to identify and interpret each subplot”s data or purpose easily. Importance of Subplot title Subplot titles help clarify the content or purpose of individual plots within a grid of subplots, especially when presenting multiple visualizations together. They aid in quickly identifying the information presented in each subplot, improving the overall interpretability of the visualizations. Syntax The below is the syntax and parameters for setting up the subplot title. ax.set_title(”Title”) Where, ax − It represents the axes object of the subplot for which the title is being set. set_title() − The method used to set the title. ”Title” − It is the string representing the text of the title. Subplots with title In this example we are creating the subplots and setting up the title for each subplot by using the set_title() method available in the Matplotlib library. Example import matplotlib.pyplot as plt import numpy as np # Generating sample data x = np.linspace(0, 10, 100) y1 = np.sin(x) y2 = np.cos(x) # Creating subplots fig, (ax1, ax2) = plt.subplots(1, 2) # Plotting on the first subplot ax1.plot(x, y1) ax1.set_title(”Sine Wave”) # Plotting on the second subplot ax2.plot(x, y2) ax2.set_title(”Cosine Wave”) # Displaying the subplots plt.show() Output Example Here in this example we are creating the subplots and adding the title to each subplot. import matplotlib.pyplot as plt import numpy as np # Generating sample data x = np.linspace(0, 10, 50) y = np.sin(x) # Generating random data for scatter plot np.random.seed(0) x_scatter = np.random.rand(50) * 10 y_scatter = np.random.rand(50) * 2 – 1 # Random values between -1 and 1 # Creating subplots fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4)) # 1 row, 2 columns # Line plot on the first subplot ax1.plot(x, y, color=”blue”, label=”Line Plot”) ax1.set_title(”Line Plot”) ax1.set_xlabel(”X-axis”) ax1.set_ylabel(”Y-axis”) ax1.legend() # Scatter plot on the second subplot ax2.scatter(x_scatter, y_scatter, color=”red”, label=”Scatter Plot”) ax2.set_title(”Scatter Plot”) ax2.set_xlabel(”X-axis”) ax2.set_ylabel(”Y-axis”) ax2.legend() # Displaying the subplots plt.show() Output Print Page Previous Next Advertisements ”;
Matplotlib – Anchored Artists ”; Previous Next In Matplotlib, an Artist is a fundamental object that represents almost all components of a plot. Whether it”s a line, text, axis, or any other graphical element, everything in a Matplotlib plot is an instance of an Artist or is derived from the Artist class. Anchored Artists are a special type of custom artist that can be anchored to specific positions on a plot. They are useful for adding annotations, arrows, and other custom elements that are anchored to a particular point or region. See the below example for refence − In the above image, you can observe that text boxes, circles, and size bars are anchored at specific positions on the plot. Anchored Artists in Matplotlib There are two modules that provides Anchored Artists in Matplotlib, which are − Matplotlib.offsetbox Mpl_toolkits.axes_grid1.anchored_artists The matplotlib.offsetbox module This module provides classes like AnchoredOffsetbox and AnchoredText, allowing you to anchor arbitrary artists or text relative to the parent axes or a specific anchor point. These can be used for more general-purpose annotations and decorations. Example Now, let”s use the AnchoredText class from the matplotlib.offsetbox module to implement two anchored text boxes at specific location on the plot. import matplotlib.pyplot as plt from matplotlib.offsetbox import AnchoredText # Create a figure and axis fig, ax = plt.subplots(figsize=(7, 4)) # Anchored Text Box 1 at = AnchoredText(“Anchored text-box 1″, loc=”upper left”, prop=dict(size=10), frameon=True) at.patch.set_boxstyle(“round,pad=0.,rounding_size=0.2”) ax.add_artist(at) # Anchored Text Box 2 at2 = AnchoredText(“Anchored text-box 2″, loc=”center”, prop=dict(size=16), frameon=True, bbox_to_anchor=(0.5, 0.5), bbox_transform=ax.transAxes) at2.patch.set_boxstyle(“round,pad=0.,rounding_size=0.5″) ax.add_artist(at2) # Display the plot plt.show() Output On executing the above code we will get the following output − The mpl_toolkits.axes_grid1.anchored_artists module This module offers specialized Anchored Artists like AnchoredDirectionArrows, AnchoredAuxTransformBox, AnchoredDrawingArea, and AnchoredSizeBar. Eachof this class is used to different porposes. Let’s see the usase of the each class − AnchoredAuxTransformBox − An anchored container with transformed coordinates. AnchoredDirectionArrows − Draw two perpendicular arrows to indicate directions. AnchoredDrawingArea − An anchored container with a fixed size and fillable DrawingArea. AnchoredSizeBar − Draw a horizontal scale bar with a center-aligned label underneath. Example This example demonstrates how to use AnchoredDirectionArrows class to add a visually appealing anchored direction arrow to the Matplotlib plot. import matplotlib.pyplot as plt import numpy as np import matplotlib.font_manager as fm from mpl_toolkits.axes_grid1.anchored_artists import AnchoredDirectionArrows np.random.seed(19680801) fig, ax = plt.subplots(figsize=(7, 4)) ax.imshow(np.random.random((10, 10))) # Rotated arrow fontprops = fm.FontProperties(family=”serif”) rotated_arrow = AnchoredDirectionArrows( ax.transAxes, ”30”, ”120”, loc=”center”, color=”w”, angle=30, fontproperties=fontprops ) ax.add_artist(rotated_arrow) plt.show() Output On executing the above code we will get the following output − Print Page Previous Next Advertisements ”;
Matplotlib – Quick Guide
Matplotlib – Quick Guide ”; Previous Next Matplotlib – Introduction Matplotlib is one of the most popular Python packages used for data visualization. It is a cross-platform library for making 2D plots from data in arrays. Matplotlib is written in Python and makes use of NumPy, the numerical mathematics extension of Python. It provides an object-oriented API that helps in embedding plots in applications using Python GUI toolkits such as PyQt, WxPythonotTkinter. It can be used in Python and IPython shells, Jupyter notebook and web application servers also. Matplotlib has a procedural interface named the Pylab, which is designed to resemble MATLAB, a proprietary programming language developed by MathWorks. Matplotlib along with NumPy can be considered as the open source equivalent of MATLAB. Matplotlib was originally written by John D. Hunter in 2003. The current stable version is 2.2.0 released in January 2018. Matplotlib – Environment Setup Matplotlib and its dependency packages are available in the form of wheel packages on the standard Python package repositories and can be installed on Windows, Linux as well as MacOS systems using the pip package manager. pip3 install matplotlib Incase Python 2.7 or 3.4 versions are not installed for all users, the Microsoft Visual C++ 2008 (64 bit or 32 bit forPython 2.7) or Microsoft Visual C++ 2010 (64 bit or 32 bit for Python 3.4) redistributable packages need to be installed. If you are using Python 2.7 on a Mac, execute the following command − xcode-select –install Upon execution of the above command, the subprocess32 – a dependency, may be compiled. On extremely old versions of Linux and Python 2.7, you may need to install the master version of subprocess32. Matplotlib requires a large number of dependencies − Python (>= 2.7 or >= 3.4) NumPy setuptools dateutil pyparsing libpng pytz FreeType cycler six Optionally, you can also install a number of packages to enable better user interface toolkits. tk PyQt4 PyQt5 pygtk wxpython pycairo Tornado For better support of animation output format and image file formats, LaTeX, etc., you can install the following − _mpeg/avconv ImageMagick Pillow (>=2.0) LaTeX and GhostScript (for rendering text with LaTeX). LaTeX and GhostScript (for rendering text with LaTeX). Matplotlib – 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. Anaconda distribution is available for installation at https://www.anaconda.com/download/. For installation on Windows, 32 and 64 bit binaries are available − https://repo.continuum.io/archive/Anaconda3-5.1.0-Windows-x86.exe https://repo.continuum.io/archive/Anaconda3-5.1.0-Windows-x86_64.exe Installation is a fairly straightforward wizard based process. You can choose between adding Anaconda in PATH variable and registering Anaconda as your default Python. For installation on Linux, download installers for 32 bit and 64 bit installers from the downloads page − https://repo.continuum.io/archive/Anaconda3-5.1.0-Linux-x86.sh https://repo.continuum.io/archive/Anaconda3-5.1.0-Linux-x86_64.sh Now, run the following command from the Linux terminal − $ bash Anaconda3-5.0.1-Linux-x86_64.sh Canopy and ActiveState are the most sought after choices for Windows, macOS and common Linux platforms. The Windows users can find an option in WinPython. Matplotlib – Jupyter Notebook Jupyter is a loose acronym meaning Julia, Python, and R. These programming languages were the first target languages of the Jupyter application, but nowadays, the notebook technology also supports many other languages. In 2001, Fernando Pérez started developing Ipython. IPython is a command shell for interactive computing in multiple programming languages, originally developed for the Python. Consider the following features provided by IPython − Interactive shells (terminal and Qt-based). A browser-based notebook with support for code, text, mathematical expressions, inline plots and other media. Support for interactive data visualization and use of GUI toolkits. Flexible, embeddable interpreters to load into one”s own projects. In 2014, Fernando Pérez announced a spin-off project from IPython called Project Jupyter. IPython will continue to exist as a Python shell and a kernel for Jupyter, while the notebook and other language-agnostic parts of IPython will move under the Jupyter name. Jupyter added support for Julia, R, Haskell and Ruby. To start the Jupyter notebook, open Anaconda navigator (a desktop graphical user interface included in Anaconda that allows you to launch applications and easily manage Conda packages, environments and channels without the need to use command line commands). Navigator displays the installed components in the distribution. Launch Jupyter Notebook from the Navigator − You will see the application opening in the web browser on the following address − http://localhost:8888. You probably want to start by making a new notebook. You can easily do this by clicking on the “New button” in the “Files tab”. You see that you have the option to make a regular text file, a folder, and a terminal. Lastly, you will also see the option to make a Python 3 notebook. Matplotlib – Pyplot API A new untitled notebook with the .ipynbextension (stands for the IPython notebook) is displayed in the new tab of the browser. matplotlib.pyplot is a collection of command style functions that make Matplotlib work like MATLAB. Each Pyplot function makes some change to a figure. For example, a function creates a figure, a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc. Types of Plots Sr.No Function & Description 1 Bar Make a bar plot. 2 Barh Make a horizontal bar plot. 3 Boxplot Make a box and whisker plot. 4 Hist Plot a histogram. 5 hist2d Make a 2D histogram plot. 6 Pie Plot a pie chart. 7 Plot Plot lines and/or markers to the Axes. 8 Polar Make a polar plot.. 9 Scatter Make a scatter plot of x vs y. 10 Stackplot Draws a stacked area plot. 11 Stem Create a stem plot.
Matplotlib – Logarithmic Axes ”; Previous Next What is Logarithmic axes? Logarithmic axes in Matplotlib allow for plots where one or both axes use a logarithmic scale rather than a linear scale. This scaling is particularly useful when dealing with a wide range of data values spanning several orders of magnitude. Instead of representing each unit equally as in linear scaling we can use logarithmic scaling which represents equal intervals in terms of orders of magnitude. Now before seeing the comparison between Linear axes and Logarithmic axes let’s go through the Linear Axes once. What is Linear Axes? Linear axes in the context of plotting and graphing refers to the standard Cartesian coordinate system where the axes are represented in a linear or arithmetic scale. In this system we have the following. X-Axis and Y-Axis − The horizontal axis is typically the x-axis representing one variable while the vertical axis is the y-axis representing another variable. Equal Spacing − The linear scale along each axis represents equal increments in the plotted values. For instance in a linear scale the distance between 0 and 1 is the same as the distance between 5 and 6. Proportional Representation − Each unit along the axis corresponds directly to a unit change in the represented value. For example moving from 10 to 11 represents the same increase as moving from 20 to 21. Straight Lines − Relationships between variables are represented as straight lines on a linear scale. For linear relationships the plotted data points form a straight line when connected. Applicability − Linear axes are suitable for visualizing data where the relationships between variables are linear or when the values being represented do not vary widely across the scale. Linear vs. Logarithmic Scales Linear and logarithmic scales are different ways to represent data on an axis in a plot each with distinct characteristics that suit different types of data distributions and visualizations. Linear Axes Logarthmic Axes Scaling This used linear scaling; the distance between each value on the axis is uniform and represents an equal increment in the plotted quantity. Logarithmic scaling represents values based on orders of magnitude rather than linear increments. Each tick on the axis corresponds to a power of a base value (e.g., 10 or e). Intervals The units along the axis correspond directly to the data values. For example on a linear scale from 0 to 10, each unit (e.g., from 0 to 1, 1 to 2) represents an equal increment of 1. In a logarithmic scale, equal distances along the axis represent multiplicative factors rather than additive ones. For example on a log scale from 1 to 100, the distances might represent powers of 10 (1, 10, 100). Representation Linear axes are typically used for data where the relationship between plotted points is best described by a linear progression. Logarithmic axes are suitable for data that spans multiple orders of magnitude, such as exponential growth or decay. They compress large ranges of values, making them visually manageable. When to use Typically used for data that shows a linear relationship between variables or data that does not span a wide range of values. Useful for visualizing data that spans several orders of magnitude, especially when dealing with exponential growth or decay, frequency distributions, or data that concentrates in certain ranges with outliers. Plot Types of Logarithmic Scales There are different types of Logarithmic scales available in Logarithmic axes. Let’s see one by one. Logarithmic X-axis A logarithmic x-axis in a plot refers to an x-axis where the scale is logarithmic rather than linear. This scaling transforms the representation of data on the x-axis from a linear progression to a logarithmic progression by making it suitable for visualizing data that spans multiple orders of magnitude or exhibits exponential behavior along the x-axis. Characteristics of Logarithmic X-axis Scaling Method − Instead of representing values in equal increments along the x-axis as in linear scaling a logarithmic x-axis represents values based on powers of a base value (e.g., 10 or e). Unequal Spacing − Equal distances on the axis correspond to multiplicative factors or orders of magnitude rather than fixed intervals. Use Case − Logarithmic x-axes are valuable when dealing with datasets that cover a wide range of values such as exponential growth, large spans of time or data distributions that concentrate in specific ranges with outliers. Example In this example plt.xscale(”log”) function sets the x-axis to a logarithmic scale. It transforms the x-axis from a linear scale to a logarithmic scale allowing for better visualization of the data especially when dealing with exponential or wide-ranging x-values. import matplotlib.pyplot as plt import numpy as np # Generating sample data x = np.linspace(1, 1000, 100) y = np.sin(x) * np.log10(x) # Generating data for demonstration # Creating a plot with logarithmic x-axis plt.figure(figsize=(8, 4)) plt.plot(x, y) plt.xscale(”log”) # Set x-axis to logarithmic scale plt.xlabel(”X-axis (Logarithmic Scale)”) plt.ylabel(”Y-axis”) plt.title(”Plot with Logarithmic X-axis”) plt.show() Output A logarithmic x-axis provides a different perspective on data visualization, emphasizing exponential behavior or patterns across varying orders of magnitude along the x-axis. Logarithmic Y-axis A logarithmic y-axis we often denoted as a log scale on the y-axis, represents a scaling method in plotting where the values along the y-axis are displayed logarithmically rather than linearly. This scaling is particularly useful when dealing with data that spans several orders of magnitude. The logarithmic y-axis in Matplotlib allows for the effective visualization of data that covers a wide range of values by making it easier to observe patterns or trends that might not be apparent when using a linear