Matplotlib – Click Events ”; Previous Next In general, a click event occurs when a user interacts with a computer interface by pressing and releasing a mouse button or tapping on a touchscreen device. This event serves as a trigger for the computer system to recognize and respond to the user”s input. In the context of data visualization, like in Matplotlib or other plotting libraries, a click event can be used to capture specific user interactions with the plot, offering a dynamic and interactive experience. This could include tasks such as selecting data points, triggering updates or enabling user-initiated actions. Click Events in Matplotlib In Matplotlib, a click event occurs when a user interacts with a plot by clicking on the figure or a specific region within it. These events are associated with callback functions that are executed when the click happens. This can be done by connecting a callback function to the button_press_event using the mpl_connect() method on the figure canvas. Let”s see a basic example that demonstrates how a simple click event works. Example In this example, a click event is handled by the onclick function, which prints a message to the console when the user clicks anywhere on the plot. The figure contains a text element prompting the user to click. import numpy as np import matplotlib.pyplot as plt def onclick(event): print(”The Click Event Triggered!”) fig, ax = plt.subplots(figsize=(7, 4)) ax.text(0.1, 0.5, ”Click me anywhere on this plot!”, dict(size=20)) cid = fig.canvas.mpl_connect(”button_press_event”, onclick) plt.show() Output On executing the above code we will get the following output − The Click Event Triggered! The Click Event Triggered! The Click Event Triggered! The Click Event Triggered! The Click Event Triggered! The Click Event Triggered! Watch the video below to observe how the click event feature works here. Storing Click Event Coordinates Storing click event coordinates allows you to gather information about user interactions on a plot, facilitating tasks such as data point selection or analysis. Example Here is an example that stores and prints the coordinates of mouse clicks on the plot. This demonstrates how click events can be used to gather information about user interactions on a plot. import numpy as np import matplotlib.pyplot as plt x = np.arange(0, 2*np.pi, 0.01) y = np.sin(x) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(x, y) clicked_coords = [] def onclick(event): global ix, iy ix, iy = event.xdata, event.ydata print(f”Clicked at x = {ix}, y = {iy}”) global clicked_coords clicked_coords.append((ix, iy)) # Disconnect the click event after collecting 5 coordinates if len(clicked_coords) == 5: fig.canvas.mpl_disconnect(cid) print(”Reached the maximum clicks…”) cid = fig.canvas.mpl_connect(”button_press_event”, onclick) plt.show() Output On executing the above code we will get the following output − Clicked at x = 0.0743760368663593, y = 0.11428680137603275 Clicked at x = 1.4368755760368663, y = 0.9928568371128363 Clicked at x = 3.130449769585254, y = 0.10714395555703438 Clicked at x = 4.7221548387096774, y = -1.014282838025715 Clicked at x = 6.377528110599078, y = 0.04285834318604875 Reached the maximum clicks… Watch the video below to observe how the click event feature works here. Click Event with Checkbox Integrating the checkbox widget with click events offers a dynamic way to control user interactions on the plots. By combining checkboxes with click events, you can enable or disable certain features, providing users with interactive control over the plot. Example In this example, a checkbox is used to control the adding text on the plot where the click event is triggered. import matplotlib.pyplot as plt from matplotlib.widgets import CheckButtons import numpy as np def onclick(event): # Only use events within the axes. if not event.inaxes == ax1: return # Check if Checkbox is “on” if check_box.get_status()[0]: ix, iy = event.xdata, event.ydata coords3.append((ix, iy)) # write text with coordinats where clicks occur if len(coords3) >= 1: ax1.annotate(f”* {ix:.1f}, {iy:.1f}”, xy=(ix, iy), color=”green”) fig.canvas.draw_idle() # Disconnect after 6 clicks if len(coords3) >= 6: fig.canvas.mpl_disconnect(cid) print(”Reached the maximum clicks…”) plt.close(fig) x = np.arange(0, 2*np.pi, 0.01) y = np.sin(2*x) fig, ax1 = plt.subplots(figsize=(7, 4)) ax1.plot(x, y) ax1.set_title(”This is my plot”) ax2 = plt.axes([0.7, 0.05, 0.1, 0.075]) check_box = CheckButtons(ax2, [”On”,], [False,], check_props={”color”:”red”, ”linewidth”:1}) coords3 = [] cid = fig.canvas.mpl_connect(”button_press_event”, onclick) plt.show() Output On executing the above code we will get the following output − Reached the maximum clicks… Watch the video below to observe how the click event feature works here. Print Page Previous Next Advertisements ”;
Category: matplotlib
Matplotlib – Histogram
Matplotlib – Histogram ”; Previous Next A histogram is like a visual summary that shows how often different values appear in a set of data. Imagine you have a collection of numbers, like ages of people. A histogram divides these numbers into groups, called “bins,” and then uses bars to represent how many numbers fall into each bin. The taller the bar, the more numbers are in that group. Histogram in Matplotlib We can create a histogram in Matplotlib using the hist() function. This function allows us to customize various aspects of the histogram, such as the number of bins, color, and transparency. Histogram in Matplotlib is used to represent the distribution of numerical data, helping you to identify patterns. The hist() Function The hist() function in Matplotlib takes a dataset as input and divides it into intervals (bins). It then displays the frequency (count) of data points falling within each bin as a bar graph. Following is the syntax of hist() function in Matplotlib − Syntax plt.hist(x, bins=None, range=None, density=False, cumulative=False, color=None, edgecolor=None, …) Where, x is the input data for which the histogram is determined. bins (optional) is the number of bins or the bin edges. range (optional) is the lower and upper range of the bins. Default is the minimum and maximum of x If density (optional) is True, the histogram represents a probability density function. Default is False. If cumulative (optional) is True, a cumulative histogram is computed. Default is False. These are just a few parameters; there are more optionals parameters available for customization. Creating a Vertical Histogram In Matplotlib, creating a vertical histogram involves plotting a graphical representation of the frequency distribution of a dataset, with the bars oriented vertically along the y-axis. Each bar represents the frequency or count of data points falling within a particular interval or bin along the x-axis. Example In the following example, we are creating a vertical histogram by setting the “orientation” parameter to “vertical” within the hist() function − import matplotlib.pyplot as plt plt.rcParams[“figure.figsize”] = [7.50, 3.50] plt.rcParams[“figure.autolayout”] = True x = [1, 2, 3, 1, 2, 3, 4, 1, 3, 4, 5] plt.hist(x, orientation=”vertical”) plt.show() Output We get the output as shown below − Customized Histogram with Density When we create a histogram with density, we are providing a visual summary of how data is distributed. We use this graph to see how likely different numbers are occurring, and the density option makes sure the total area under the histogram is normalized to one. Example In the following example, we are visualizing random data as a histogram with 30 bins, displaying it in green with a black edge. We are using the density=True parameter to represent the probability density − import matplotlib.pyplot as plt import numpy as np # Generate random data data = np.random.randn(1000) # Create a histogram with density and custom color plt.hist(data, bins=30, density=True, color=”green”, edgecolor=”black”, alpha=0.7) plt.xlabel(”Values”) plt.ylabel(”Probability Density”) plt.title(”Customized Histogram with Density”) plt.show() Output After executing the above code, we get the following output − Cumulative Histogram When we create a cumulative histogram, we graphically represent the total number of occurrences of values up to a certain point. It shows how many data points fall below or equal to a certain value. Example In here, we are using a histogram where each bar represents a range of exam scores, and the height of the bar tells us how many students, in total, scored within that range. By setting the cumulative=True parameter in the hist() function, we make sure that the histogram shows the cumulative progression of scores − import matplotlib.pyplot as plt import numpy as np # Generate random exam scores (out of 100) exam_scores = np.random.randint(0, 100, 150) # Create a cumulative histogram plt.hist(exam_scores, bins=20, cumulative=True, color=”orange”, edgecolor=”black”, alpha=0.7) plt.xlabel(”Exam Scores”) plt.ylabel(”Cumulative Number of Students”) plt.title(”Cumulative Histogram of Exam Scores”) plt.show() Output Following is the output of the above code − Histogram with Different Color and Edge Color When creating a histogram, we can customize the fill color and edge color, adding a visual touch to represent the data distribution. By doing this, we blend the histogram with a stylish and distinctive appearance. Example Now, we are generating a histogram for random data with 25 bins, and we are presenting it in purple color with blue edges − import matplotlib.pyplot as plt import numpy as np data = np.random.randn(1000) # Creating a histogram with different color and edge color plt.hist(data, bins=25, color=”purple”, edgecolor=”blue”) plt.xlabel(”Values”) plt.ylabel(”Frequency”) plt.title(”Histogram with Different Color and Edge Color”) plt.show() Output On executing the above code we will get the following output − Example To plot a histogram with colors, we can also extract colors from the “cm” parameter in the setp() method. import numpy as np from matplotlib import pyplot as plt plt.rcParams[“figure.figsize”] = [7.00, 3.50] plt.rcParams[“figure.autolayout”] = True data = np.random.random(1000) n, bins, patches = plt.hist(data, bins=25, density=True, color=”red”, rwidth=0.75) col = (n-n.min())/(n.max()-n.min()) cm = plt.cm.get_cmap(”RdYlBu”) for c, p in zip(col, patches): plt.setp(p, ”facecolor”, cm(c)) plt.show() Output On executing the above code we will get the following output − Example In here, we are specifying different colors for different bars in a matplotlib histogram by iterating in the range of number of bins and setting random facecolor for each bar − import numpy as np import matplotlib.pyplot as plt import random import string # Set the figure size plt.rcParams[“figure.figsize”] = [7.50, 3.50] plt.rcParams[“figure.autolayout”] = True # Figure and set of subplots fig, ax = plt.subplots() # Random data data = np.random.rand(100) # Plot
Matplotlib – Background Colors ”; Previous Next What are Background Colors in Matplotlib? Matplotlib provides extensive options to control background colors enabling users to customize the visual appearance of plots and figures. The background color plays a crucial role in enhancing the aesthetics and readability of visualizations, setting the tone and mood for the displayed data. The following are the different features available in the Background colors of Matplotlib library. Let’s see each one in detailed view. Figure and Plot Background Color The figure”s background color encompasses the entire area where plots are rendered. By default it”s often white but it can be changed using plt.figure(facecolor=”color_name”) or plt.gcf().set_facecolor(”color_name”). This affects the area around the plots. The plot background color on the other hand refers to the area within the plot”s axes. It can be altered with plt.gca().set_facecolor(”color_name”) by providing a different background color within the actual plot. Changing Figure Bacground color In this example demonstrating how to set the background color for the figure using Matplotlib library. Example import matplotlib.pyplot as plt import numpy as np # Generating data x = np.linspace(0, 10, 100) y = np.sin(x) # Changing Figure Background Color plt.figure(facecolor=”lightblue”) # Set figure background color plt.plot(x, y) plt.title(”Figure Background Color Example”) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.show() Output Changing Plot Area Background Color In this example we use plt.gca().set_facecolor(”lightgreen”) to set the background color for the plot area specifically. Example import matplotlib.pyplot as plt import numpy as np # Generating data x = np.linspace(0, 10, 100) y = np.sin(x) # Changing plot area Background Color plt.plot(x, y) plt.gca().set_facecolor(”lightgreen”) # Set plot area background color plt.title(”Plot Area Background Color Example”) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.show() Output Stylesheets for Background Colors Matplotlib offers stylesheets that provide predefined configurations including background colors. Stylesheets like ”dark_background”, ”ggplot” or ”seaborn” have distinctive color schemes that affect the background color of plots, figures and other elements. Stylesheets not only modify the background colors but also encompass various other stylistic elements such as line colors, text sizes and grid styles. Experimenting with different stylesheets allows us to quickly explore and visualize how different styles affect the appearance of our plots. Example Here”s an example showcasing how stylesheets in Matplotlib can be used to modify import matplotlib.pyplot as plt import numpy as np # Generating data x = np.linspace(0, 10, 100) y = np.sin(x) # Plot using different stylesheets stylesheets = [”ggplot”, ”dark_background”, ”seaborn-poster”] for style in stylesheets: plt.style.use(style) # Apply the selected stylesheet plt.plot(x, y) plt.title(f”Plot with {style.capitalize()} Stylesheet”) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.show() Output Impact on Visualization Background colors influence the visual perception of data. Dark backgrounds might emphasize bright or contrasting data while light backgrounds often offer a clean and conventional look suitable for most contexts. Background colors should be chosen carefully to ensure readability and accessibility for viewers. Customization and Color Representation We can customize background colors using various representations such as color names (”blue”, ”red”), hexadecimal strings (”#RRGGBB”), RGB tuples ((0.1, 0.2, 0.5)), or RGBA tuples with alpha transparency ((0.1, 0.2, 0.5, 0.3)). These color string representations offer flexibility in specifying colors for various elements within the plot by allowing us to precisely control the visual appearance of our visualizations. We can use named colors, hexadecimal strings, RGB tuples or RGBA values to customize colors for different elements in Matplotlib plots. Customizing with Color Strings We can directly use color names or hexadecimal strings to set the background color. Example import matplotlib.pyplot as plt import numpy as np # Generating data x = np.linspace(0, 10, 100) y = np.sin(x) # Customizing with color strings plt.figure(facecolor=”green”) # Set figure background color using color name plt.plot(x, y) plt.title(”Customizing with Color Strings”) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.show() Output Customization Options We can also customize other elements using color strings or RGB values such as line colors, marker colors or even modifying the color of specific text elements in the plot. Example import matplotlib.pyplot as plt import numpy as np # Generating data x = np.linspace(0, 10, 100) y = np.sin(x) # Customizing with color strings plt.figure(facecolor=”lightblue”) # Set figure background color using color name plt.plot(x, y, color=”orange”) # Set line color using a color name plt.scatter(x, y, color=”#00FF00”) # Set marker color using hexadecimal color string plt.xlabel(”X-axis”, color=”red”) # Set x-axis label color using a color name plt.ylabel(”Y-axis”, color=(0.5, 0.1, 0.7)) # Set y-axis label color using RGB tuple plt.show() Output Importance of Background Colors The choice of background color significantly impacts the aesthetics and interpretation of visualizations. It can affect readability, visual contrast and the overall impression of the displayed data. Context, audience and the specific purpose of the visualization should guide the selection of background colors. Use Cases Contrast and Visibility − Contrast between data elements and the background can be adjusted to highlight or de-emphasize certain information. Themes and Branding − Background colors can align with branding or thematic considerations by ensuring consistency across multiple visualizations. Accessibility − Selecting appropriate background color is very crucial for ensuring accessibility, especially for individuals with visual impairments. Matplotlib offers diverse options for controlling background colors in plots and figures. These choices have a substantial impact on the aesthetics, readability and interpretation of visualization by making them a fundamental aspect of creating effective and engaging plots. Properly chosen background colors enhance the overall appeal and communication of data representations. Change the default background color In this example we will change the default background color for Matplotlib plots. Example import numpy as np import matplotlib.pyplot as plt plt.rcParams[“figure.figsize”] = [7.50, 3.50] plt.rcParams[“figure.autolayout”] = True ax = plt.gca() print(“Default face color is: “, ax.get_facecolor()) plt.subplot(121) plt.plot(np.random.rand(10), np.random.rand(10)) plt.title(“With default face color”) plt.subplot(122) ax = plt.gca() ax.set_facecolor(“orange”)
Matplotlib – Compound Path
Matplotlib – Compound Path ”; Previous Next In graphics and design, a “path” is a sequence of points connected by lines or curves. It is like drawing a line from one point to another. “Compound” means made up of multiple parts or elements. Imagine you have several basic shapes like circles, rectangles, and lines. Individually, these shapes are simple and limited in what they can represent. However, by combining them together in different arrangements and orientations, you can create more complex and interesting shapes. This process of combining simple shapes to create more complex ones is what is referred to as using compound paths. Compound Path in Matplotlib A compound path in Matplotlib refers to a combination of multiple simple paths or shapes that are grouped together to form a more complex shape. These simple paths could be lines, curves, polygons, or other basic shapes. In Matplotlib, you can create compound paths using the “Path” class, which allows you to define custom paths by specifying the vertices and codes that describe the path segments. You can then use these custom paths to draw complex shapes or patterns on your plots. Compound Path: Intersection of Circle and Rectangle A compound path of the intersection of a circle and a rectangle in Matplotlib refers to creating a single shape that represents the area where the circle and the rectangle overlap or intersect. Instead of treating the circle and the rectangle as separate entities, you combine them together to form a new, more complex shape that captures the common region where they intersect. In Matplotlib, you can create a compound path of the intersection of a circle and a rectangle by defining the vertices and codes that describe the path segments for each shape. Then, you combine these paths together to form the compound path representing the intersection. Once created, you can use this compound path to draw the intersecting area on your plot. Example In the following example, we are creating a compound path representing the intersection of a circle and a rectangle by combining their vertices and codes into a single Path object − import matplotlib.pyplot as plt from matplotlib.path import Path from matplotlib.patches import PathPatch # Defining the paths for the shapes circle = Path.unit_circle() rect = Path([(0.5, 0.5), (0.5, 1.5), (1.5, 1.5), (1.5, 0.5), (0.5, 0.5)], closed=True) # Combining the paths into a compound path (Intersection) compound_vertices = circle.vertices.tolist() + rect.vertices.tolist() compound_codes = circle.codes.tolist() + rect.codes.tolist() compound_path = Path(compound_vertices, compound_codes) # Plotting the compound path fig, ax = plt.subplots() patch = PathPatch(compound_path, facecolor=”blue”, edgecolor=”black”) ax.add_patch(patch) # Setting plot limits and aspect ratio ax.set_xlim(0, 2) ax.set_ylim(0, 2) ax.set_aspect(”equal”) # Showing the plot plt.title(”Intersection of Circle and Rectangle”) plt.show() Output Following is the output of the above code − Compound Path of Union of Two Rectangles A compound path of the union of two rectangles in Matplotlib refers to creating a single shape by combining the areas covered by two separate rectangles. Instead of treating the rectangles as individual shapes, you merge them together to form a new, more complex shape. In Matplotlib, you can create a compound path of the union of two rectangles by defining the vertices and codes that describe the path segments for each rectangle. Then, you combine these paths together to form the compound path representing the union of the rectangles. Once created, you can use this compound path to draw the combined shape on your plot. Example In here, we are creating a compound path representing the union of two rectangles by combining their vertices and codes into a single Path object − import matplotlib.pyplot as plt from matplotlib.path import Path from matplotlib.patches import PathPatch # Defining the paths for the shapes # Rectangle 1 path1 = Path([(1, 1), (1, 2), (2, 2), (2, 1), (1, 1)], closed=True) # Rectangle 2 path2 = Path([(1.5, 0), (1.5, 1), (2.5, 1), (2.5, 0), (1.5, 0)], closed=True) # Combining the paths into a compound path (Union) compound_vertices = path1.vertices.tolist() + path2.vertices.tolist() compound_codes = path1.codes.tolist() + path2.codes.tolist() compound_path = Path(compound_vertices, compound_codes) # Plotting the compound path fig, ax = plt.subplots() patch = PathPatch(compound_path, facecolor=”blue”, edgecolor=”black”) ax.add_patch(patch) # Setting plot limits and aspect ratio ax.set_xlim(0, 3) ax.set_ylim(0, 2.5) ax.set_aspect(”equal”) # Displaying the plot plt.title(”Union of Two Rectangles”) plt.show() Output On executing the above code we will get the following output − Compound Path: Difference of Two Circles A compound path of the difference of two circles in Matplotlib refers to creating a single shape that represents the area remaining when one circle is subtracted from another. In Matplotlib, you can create a compound path of the difference of two circles by defining the vertices and codes that describe the path segments for each circle. Then, you combine these paths together and subtract the path of the smaller circle from the path of the larger circle to form the compound path representing the difference. Once created, you can use this compound path to draw the remaining ring-shaped area on your plot. Example Now, we are creating a compound path representing the difference between two circles by combining their vertices and codes into a single Path object − import matplotlib.pyplot as plt from matplotlib.path import Path from matplotlib.patches import PathPatch import numpy as np # Defining the paths for the shapes circle1 = Path.unit_circle() circle2 = Path.unit_circle().transformed(plt.matplotlib.transforms.Affine2D().scale(0.5)) # Combining the paths into a compound path (Difference) compound_vertices = np.concatenate([circle1.vertices, circle2.vertices]) compound_codes = np.concatenate([circle1.codes, circle2.codes]) compound_path = Path(compound_vertices, compound_codes) # Plotting the compound path fig, ax = plt.subplots() patch = PathPatch(compound_path, facecolor=”blue”, edgecolor=”black”) ax.add_patch(patch) # Setting plot limits and aspect ratio ax.set_xlim(-1, 2) ax.set_ylim(-1, 2) ax.set_aspect(”equal”) # Displaying the plot plt.title(”Difference of Two Circles”) plt.show() Output
Matplotlib – Close Event
Matplotlib – Close Event ”; Previous Next In the context of programming and software design, an event refers to an action or incident that is identified by the software. These events can be initiated by the system, user inputs, or other sources and are subject to handling by the software. Specifically, a close event is an occurrence triggered when a figure is closed within the software interface. This event means the termination or closure of the graphical representation or window associated with the figure and reminds the software to respond accordingly. Close Events in Matplotlib Matplotlib provides a set of tools to handle events, among them is the ability to handle close events. A close event in Matplotlib occurs when a figure window is closed, triggering specific actions within your Python script. By connecting to the close_event you can execute custom code in response to a figure being closed. In this tutorial, we will explore how to use close events in Matplotlib to enhance interactive plots. Example Here is a simple example that displays a message when the user closes the figure. import matplotlib.pyplot as plt def on_close(event): print(”The Figure is Closed!”) fig, ax = plt.subplots(figsize=(7, 4)) ax.annotate(”X”, xy=(1, 1), xytext=(0.9, 0.65), fontsize=20, arrowprops=dict(facecolor=”red”), horizontalalignment=”left”, verticalalignment=”bottom”) fig.canvas.mpl_connect(”close_event”, on_close) ax.text(0.15, 0.5, ”Close This Figure!”, dict(size=30)) plt.show() Output On executing the above code we will get the following output − After closing the above output figure, the following message is displayed in the console − The Figure is Closed! Detecting Closed Axes When dealing with multiple axes in a figure, you need to determine if a specific axis has been closed you can use the close event action in Matlotlib. Example Here is an example that demonstrates how to determine if a specific axis has been closed or not, using the close event in Matplotlib. import matplotlib.pyplot as plt # Function to handle the event def on_close(event): event.canvas.figure.axes[0].has_been_closed = True print(”The Figure is Closed!”) # Create the figure fig, ax = plt.subplots(figsize=(7, 4)) ax.set_title(”Detecting Closed Axes”) ax.has_been_closed = False ax.plot(range(10)) # connect the event with the callable function fig.canvas.mpl_connect(”close_event”, on_close) plt.show() print(”Check the attribute has_been_closed:”, ax.has_been_closed) Output On executing the above program you will get the following output − After closing the above output figure, the following message is displayed in the console − The Figure is Closed! Check the attribute has_been_closed: True Continuing Code After Closing In some cases, it may be necessary for your code to continue running even after the figure is closed (close event triggered). This is particularly useful for background processes or animations. Example The following example demonstrates how to continue code execution after the figure is closed. import matplotlib.pyplot as plt import matplotlib.animation as animation import numpy as np import time close_flag = 0 def handle_close(evt): global close_flag close_flag = 1 print(”The Figure is Closed!”) # Activate interactive mode plt.ion() fig, ax = plt.subplots() # listen to close event fig.canvas.mpl_connect(”close_event”, handle_close) # Generating x values x = np.arange(0, 2*np.pi, 0.01) y = np.sin(x) # Plotting the initial sine curve line, = ax.plot(x, y) ax.legend([r”$sin(x)$”]) # Function to update the plot for each frame of the animation def update(frame): line.set_ydata(np.sin(x + frame / 50)) return line t = 0 delta_t = 0.1 while close_flag == 0: if abs(t – round(t)) < 1e-5: print(round(t)) x = x + delta_t y = y – delta_t # Creating a FuncAnimation object ani = animation.FuncAnimation(fig=fig, func=update, frames=40, interval=30) # draw the figure fig.canvas.draw() fig.canvas.flush_events() # wait a little bit of time time.sleep(delta_t) t += delta_t if close_flag == 1: break print(”ok”) Output On executing the above program you will get the following output − After closing the above output figure, the following message is displayed in the console − 0 1 2 3 4 5 The Figure is Closed! ok Watch the video below to observe how the close event feature works here. Print Page Previous Next Advertisements ”;
Matplotlib – PyLab module
Matplotlib – PyLab module ”; Previous Next PyLab is a procedural interface to the Matplotlib object-oriented plotting library. Matplotlib is the whole package; matplotlib.pyplot is a module in Matplotlib; and PyLab is a module that gets installed alongside Matplotlib. PyLab is a convenience module that bulk imports matplotlib.pyplot (for plotting) and NumPy (for Mathematics and working with arrays) in a single name space. Although many examples use PyLab, it is no longer recommended. Basic Plotting Plotting curves is done with the plot command. It takes a pair of same-length arrays (or sequences) − from numpy import * from pylab import * x = linspace(-3, 3, 30) y = x**2 plot(x, y) show() The above line of code generates the following output − To plot symbols rather than lines, provide an additional string argument. symbols – , –, -., , . , , , o , ^ , v , , s , + , x , D , d , 1 , 2 , 3 , 4 , h , H , p , | , _ colors b, g, r, c, m, y, k, w Now, consider executing the following code − from pylab import * x = linspace(-3, 3, 30) y = x**2 plot(x, y, ”r.”) show() It plots the red dots as shown below − Plots can be overlaid. Just use the multiple plot commands. Use clf() to clear the plot. from pylab import * plot(x, sin(x)) plot(x, cos(x), ”r-”) plot(x, -sin(x), ”g–”) show() The above line of code generates the following output − Print Page Previous Next Advertisements ”;
Matplotlib – Image Thumbnail
Matplotlib – Image Thumbnail ”; Previous Next Thumbnails, smaller and compressed versions of original images, serve as essential components in various applications, including image previews, web development, and optimizing the loading speed of web pages and applications with heavy images. In this tutorial, we”ll explore using Matplotlib to efficiently generate image thumbnails. Matplotlib takes the support of the Python Pillow library for image processing and allows us to easily generate thumbnails from existing images. Image thumbnail in Matplotlib Matplotlib offers the thumbnail() function within its image module to generate thumbnails with customizable parameters, allowing users to efficiently create scaled-down versions of images for various purposes. Following is the syntax of the function − Syntax matplotlib.image.thumbnail(infile, thumbfile, scale=0.1, interpolation=”bilinear”, preview=False) Here are the details of its parameters − infile − The input image file. As you know that Matplotlib relies on Pillow for image reading, so it supports a wide range of file formats, including PNG, JPG, TIFF, and others. thumbfile − The filename or file-like object where the thumbnail will be saved. scale − The scale factor for the thumbnail. It determines the size reduction of the thumbnail relative to the original image. A smaller scale factor generates a smaller thumbnail. interpolation − The interpolation scheme used in the resampling process. This parameter specifies the method used to estimate pixel values in the thumbnail. preview − If set to True, the default backend (presumably a user interface backend) will be used, which may raise a figure if show() is called. If set to False, the figure is created using FigureCanvasBase, and the drawing backend is selected as Figure.savefig would normally do. The function returns a Figure instance containing the thumbnail. This Figure object can be further manipulated or saved as needed. Generating Thumbnails for a single image Matplotlib supports various image formats like png, pdf, ps, eps svg, and more, making it flexible for different use cases. Example Here is an example that creates a thumbnail for a single .jpg image. import matplotlib.pyplot as plt import matplotlib.image as mpimg input_image_path = “Images/Tajmahal.jpg” output_thumbnail_path = “Images/Tajmahal_thumbnail.jpg” # Load the original image img = mpimg.imread(input_image_path) # Create a thumbnail using Matplotlib thumb = mpimg.thumbnail(input_image_path, output_thumbnail_path, scale=0.15) print(f”Thumbnail generated for {input_image_path}. Saved to {output_thumbnail_path}”) Output If you visit the folder where the images are saved you can observe both the original and output Thumbnail images as shown below − Generating Thumbnails for multiple Images Consider a scenario where you have multiple images in a directory, and you want to generate thumbnails for each of them. Example Here is an example that creates thumbnails of multiple PNG images in a directory. Save the following script as generate_thumbnails.py file. from argparse import ArgumentParser from pathlib import Path import sys import matplotlib.image as image parser = ArgumentParser(description=”Generate thumbnails of PNG images in a directory.”) parser.add_argument(“imagedir”, type=Path) args = parser.parse_args() if not args.imagedir.is_dir(): sys.exit(f”Could not find the input directory {args.imagedir}”) outdir = Path(“thumbs”) outdir.mkdir(parents=True, exist_ok=True) for path in args.imagedir.glob(“*.png”): outpath = outdir / path.name try: fig = image.thumbnail(path, outpath, scale=0.15) print(f”Saved thumbnail of {path} to {outpath}”) except Exception as e: print(f”Error generating thumbnail for {path}: {e}”) Then run the script as follows in command prompt python generate_thumbnails.py /path/to/all_images Output On executing the above program, will create a directory named “thumbs” and generate thumbnails for PNG images in your working directory. If it encounters an image with a different format, it will print an error message and continue processing other images. Saved thumbnail of Images3d_Star.png to thumbs3d_Star.png Saved thumbnail of Imagesballoons_noisy.png to thumbsballoons_noisy.png Saved thumbnail of Imagesbinary image.png to thumbsbinary image.png Saved thumbnail of Imagesblack and white.png to thumbsblack and white.png Saved thumbnail of ImagesBlack1.png to thumbsBlack1.png Saved thumbnail of ImagesBlank.png to thumbsBlank.png Saved thumbnail of ImagesBlank_img.png to thumbsBlank_img.png Saved thumbnail of ImagesCircle1.png to thumbsCircle1.png Saved thumbnail of ImagesColorDots.png to thumbsColorDots.png Saved thumbnail of Imagescolorful-shapes.png to thumbscolorful-shapes.png Saved thumbnail of Imagesdark_img1.png to thumbsdark_img1.png Saved thumbnail of Imagesdark_img2.png to thumbsdark_img2.png Saved thumbnail of Imagesdecore.png to thumbsdecore.png Saved thumbnail of Imagesdeform.png to thumbsdeform.png Saved thumbnail of ImagesDifferent shapes.png to thumbsDifferent shapes.png Error generating thumbnail for ImagesDifferent shapes_1.png: not a PNG file Saved thumbnail of ImagesEllipses.png to thumbsEllipses.png Error generating thumbnail for ImagesEllipses_and_circles.png: not a PNG file Saved thumbnail of Imagesimages (1).png to thumbsimages (1).png Saved thumbnail of Imagesimages (3).png to thumbsimages (3).png Saved thumbnail of Imagesimages.png to thumbsimages.png Saved thumbnail of Imagesimage___1.png to thumbsimage___1.png Saved thumbnail of ImagesLenna.png to thumbsLenna.png Saved thumbnail of Imageslogo-footer-b.png to thumbslogo-footer-b.png Saved thumbnail of Imageslogo-w.png to thumbslogo-w.png Saved thumbnail of Imageslogo.png to thumbslogo.png Saved thumbnail of Imageslogo_Black.png to thumbslogo_Black.png Print Page Previous Next Advertisements ”;
Matplotlib – Axis Scales
Matplotlib – Axis Scales ”; Previous Next What is Axis Scale? In Matplotlib library, axis scales refer to the method by which the values along an axis are displayed and spaced. Matplotlib supports various types of scales that affect how data is visualized and distributed along the axes. There are different common Axis Scales in matplotlib library. They are, Linear Scale (Default) Logarithmic Scale Symmetrical Logarithmic Scale (Symlog) Choosing the appropriate axis scale depends on the nature of your data and the desired visualization. It”s important to select a scale that effectively represents your data to convey accurate information in the plot. Use Cases for Different Scales Linear − Suitable for displaying data with uniform spacing between values. Logarithmic − Useful for representing data covering a wide range of magnitudes. Symmetrical Logarithmic − Ideal for datasets containing both positive and negative values without excluding zero. Implementing Different Scales Let’s see each and every scale in detail how they should be implemented in the plots. Linear Scale In Matplotlib the linear scale represents a standard linear coordinate system used for plotting data. It is the default scaling applied to both the x-axis and y-axis unless specified otherwise. Characteristics of Linear Scale Uniform Spacing − On a linear scale equal increments along the axis represent equal differences in the data. For instance the distance between 0 and 1 is the same as between 1 and 2. Linear Relationship − Data points plotted on a linear scale adhere to a linear relationship where changes in the plotted points are proportional to the changes in the data. Example In this example the x-axis and y-axis use a linear scale by default. Each unit along the axis represents a constant increment in the data. import matplotlib.pyplot as plt # Sample data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Creating a plot with linear scale (default) plt.plot(x, y) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Plot with Linear Scale”) plt.show() Output Logarithmic Scale In Matplotlib we can set a logarithmic scale for an axis using the plt.xscale() and plt.yscale() functions or their corresponding methods ax.set_xscale() and ax.set_yscale() when working with an axis object ax. These functions allow us to change the scale of the axis to logarithmic. Syntax The below is the syntax for changing the x-axis to the logarithmic scale using, plt.xscale() − plt.xscale(”log”) ax.set_xscale() ax.set_xscale(”log”) The below is the syntax for changing the y-axis to the logarithmic scale using, plt.yscale() − plt.yscale(”log”) Using ax.set_yscale() ax.set_yscale(”log”) Example Here”s an example demonstrating how to set a logarithmic scale for the x-axis and y-axes import matplotlib.pyplot as plt # Sample data x = [1, 2, 3, 4, 5] y = [10, 100, 1000, 10000, 100000] # Creating a plot with logarithmic scale on both axes plt.plot(x, y) # Setting logarithmic scale for x-axis and y-axis plt.xscale(”log”) plt.yscale(”log”) plt.xlabel(”X-axis (Log Scale)”) plt.ylabel(”Y-axis (Log Scale)”) plt.title(”Logarithmic Scale Plot”) plt.show() Output Symmetrical Logarithmic Scale (Symlog) In Matplotlib the symmetric logarithmic scale is often referred to as symlog which allows plotting data on a logarithmic scale while also accommodating both positive and negative values symmetrically around zero. The symlog scale combines linear scaling for values close to zero and logarithmic scaling for values farther from zero. Syntax Here”s the syntax to set a symmetric logarithmic scale for an axis − For the x-axis plt.xscale(”symlog”, linthresh=base, linscale=lin_scale) For the y-axis plt.yscale(”symlog”, linthresh=base, linscale=lin_scale) Where, linthresh − Linear threshold value that determines where the transition between linear and logarithmic behavior occurs. base − Base value for the logarithm (default is 10). linscale − Scale factor for the linear range close to zero (default is 1.0). Example In this example plt.yscale(”symlog”, linthresh=0.1) sets the y-axis to a symmetric logarithmic scale with a linear threshold (linthresh) of 0.1. Values closer to zero will be displayed linearly while those farther from zero will follow a logarithmic scale. import matplotlib.pyplot as plt import numpy as np x = np.linspace(-10, 10, 500) y = np.sinh(x) plt.plot(x, y) plt.yscale(”symlog”, linthresh=0.1) # Applying symmetric logarithmic scale for y-axis plt.title(”Plot with Symmetric Logarithmic Scale”) plt.show() Output Plot with Different Scales In this example we are plotting the plot with different scales using the matplotlib library. Example import numpy as np import matplotlib.pyplot as plt plt.rcParams[“figure.figsize”] = [7.50, 3.50] plt.rcParams[“figure.autolayout”] = True t = np.arange(0.01, 10.0, 0.01) data1 = np.exp(t) data2 = np.sin(2 * np.pi * t) fig, ax1 = plt.subplots() color = ”red” ax1.set_xlabel(”time (s)”) ax1.set_ylabel(”exp”, color=color) ax1.plot(t, data1, color=color) ax1.tick_params(axis=”y”, labelcolor=color) ax2 = ax1.twinx() color = ”blue” ax2.set_ylabel(”sin”, color=color) ax2.plot(t, data2, color=color) ax2.tick_params(axis=”y”, labelcolor=color) plt.show() Output Multiple axes in Matplotlib with different scales In this example we will see how to create a shared Y-axis. Example import matplotlib.pyplot as plt fig, ax1 = plt.subplots() ax1.plot([1, 2, 3, 4, 5], [3, 5, 7, 1, 9], color=”red”) ax2 = ax1.twinx() ax2.plot([11, 12, 31, 41, 15], [13, 51, 17, 11, 76], color=”blue”) fig.tight_layout() plt.show() Output Print Page Previous Next Advertisements ”;
Matplotlib – Object-oriented Interface ”; Previous Next While it is easy to quickly generate plots with the matplotlib.pyplot module, the use of object-oriented approach is recommended as it gives more control and customization of your plots. Most of the functions are also available in the matplotlib.axes.Axes class. The main idea behind using the more formal object-oriented method is to create figure objects and then just call methods or attributes off of that object. This approach helps better in dealing with a canvas that has multiple plots on it. In object-oriented interface, Pyplot is used only for a few functions such as figure creation, and the user explicitly creates and keeps track of the figure and axes objects. At this level, the user uses Pyplot to create figures, and through those figures, one or more axes objects can be created. These axes objects are then used for most plotting actions. To begin with, we create a figure instance which provides an empty canvas. fig = plt.figure() Now add axes to figure. The add_axes() method requires a list object of 4 elements corresponding to left, bottom, width and height of the figure. Each number must be between 0 and 1 − ax=fig.add_axes([0,0,1,1]) Set labels for x and y axis as well as title − ax.set_title(“sine wave”) ax.set_xlabel(”angle”) ax.set_ylabel(”sine”) Invoke the plot() method of the axes object. ax.plot(x,y) If you are using Jupyter notebook, the %matplotlib inline directive has to be issued; the otherwistshow() function of pyplot module displays the plot. Consider executing the following code − from matplotlib import pyplot as plt import numpy as np import math x = np.arange(0, math.pi*2, 0.05) y = np.sin(x) fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.plot(x,y) ax.set_title(“sine wave”) ax.set_xlabel(”angle”) ax.set_ylabel(”sine”) plt.show() Output The above line of code generates the following output − The same code when run in Jupyter notebook shows the output as shown below − Print Page Previous Next Advertisements ”;
Matplotlib – Multipage PDF
Matplotlib – Multipage PDF ”; Previous Next A multipage PDF(Portable Document Format) is a type of file that can store multiple pages or images in a single document. Each page within the PDF can have different content, such as plots, images, or text. Matplotlib provides support for creating multipage PDFs through its backend_pdf.PdfPages module. This feature allows users to save plots and visualizations across multiple pages within the same PDF file. In certain situations, it becomes necessary to save several plots in one file. While many image file formats like PNG, SVG, or JPEG typically support only a single image per file, Matplotlib provides a solution for creating multipage output. PDF is one such supported format, allowing users to organize and share visualizations effectively. Creating a Basic multipage PDF To save plots on multiple pages in a PDF document using Matplotlib, you can make use of the PdfPages class. This class simplifies the process of generating a PDF file with several pages, each containing different visualizations. Example Let”s start with a basic example demonstrating how to create a multipage PDF with Matplotlib. This example saves multiple figures in one PDF file at once. from matplotlib.backends.backend_pdf import PdfPages import numpy as np import matplotlib.pyplot as plt # sample data for plots x1 = np.arange(10) y1 = x1**2 x2 = np.arange(20) y2 = x2**2 # Create a PdfPages object to save the pages pp = PdfPages(”Basic_multipage_pdf.pdf”) def function_plot(X,Y): plt.figure() plt.clf() plt.plot(X,Y) plt.title(”y vs x”) plt.xlabel(”x axis”, fontsize = 13) plt.ylabel(”y axis”, fontsize = 13) pp.savefig() # Create and save the first plot function_plot(x1,y1) # Create and save the second plot function_plot(x2,y2) pp.close() Output On executing the above program, ”Basic_multipage_pdf.pdf” will be generated in the directory where the script is saved. Adding Metadata and Annotations Matplotlib also supports the addition of metadata and annotations to a multipage PDF. Metadata can include information such as the title, author, and creation date, providing additional context or details about the content within the PDF. Example Here is an advanced example, that creates a multipage PDF with metadata and annotations. import datetime import matplotlib.pyplot as plt import numpy as np from matplotlib.backends.backend_pdf import PdfPages # Create the PdfPages object to save the pages with PdfPages(”Advanced_multipage_pdf.pdf”) as pdf: # Page One plt.figure(figsize=(3, 3)) plt.plot(range(7), [3, 1, 4, 1, 5, 9, 2], ”r-o”) plt.title(”Page One”) # saves the current figure into a pdf page pdf.savefig() plt.close() # Page Two # Initially set it to True. If LaTeX is not installed or an error is caught, change to `False` # The usetex setting is particularly useful when you need LaTeX features that aren”t present in matplotlib”s built-in mathtext. plt.rcParams[”text.usetex”] = False plt.figure(figsize=(8, 6)) x = np.arange(0, 5, 0.1) plt.plot(x, np.sin(x), ”b-”) plt.title(”Page Two”) # attach metadata (as pdf note) to page pdf.attach_note(“plot of sin(x)”) pdf.savefig() plt.close() # Page Three plt.rcParams[”text.usetex”] = False fig = plt.figure(figsize=(4, 5)) plt.plot(x, x ** 2, ”ko”) plt.title(”Page Three”) pdf.savefig(fig) plt.close() # Set file metadata d = pdf.infodict() d[”Title”] = ”Multipage PDF Example” d[”Author”] = ”Tutorialspoint” d[”Subject”] = ”How to create a multipage pdf file and set its metadata” d[”Keywords”] = ”PdfPages multipage keywords author title subject” d[”CreationDate”] = datetime.datetime(2024, 1, 15) d[”ModDate”] = datetime.datetime.today() Output On executing the above program, ”Advanced_multipage_pdf.pdf” will be generated in the directory where the script is saved. you will be able to observe the details like below − Print Page Previous Next Advertisements ”;