Matplotlib – Coords Report

Matplotlib – Coords Report ”; Previous Next A coords report, short for “coordinates report,” is a document or data file that contains information about different locations or points on a map. These locations are described using coordinates, which are like a set of directions that pinpoint exactly where something is on the Earth”s surface. Imagine you have a big map of your neighborhood, and you want to tell someone exactly where your house is. You can give them the coordinates, which are like the map”s secret code for your house”s exact location. This code might look something like this: Latitude 40.7128° N, Longitude 74.0060° W − Coords Report in Matplotlib In Matplotlib, a coordinates report provides information about the position of points or objects within a plot. This report includes details such as the x-coordinate and y-coordinate of each point, as well as any additional properties like size, color, or label. You create a coord report or any other type of plot that involves coordinates in Matplotlib using the scatter() function. This function takes two arguments: x and y, which represent the coordinates of the points to be plotted. Scatter Plot Coord Report In Matplotlib, a scatter plot coordinate report provides detailed information about the individual data points displayed in a scatter plot. This report includes the x and y coordinates of each point, allowing you to precisely identify your positions on the plot. Additionally, it may contain other properties such as the size, color, or label associated with each data point. Example In the following example, we are creating a scatter plot with two sets of data: x and y, where x represents the values on the x-axis and y represents the corresponding values on the y-axis. Additionally, we iterate through each pair of coordinates in x and y using a for loop, and for each point, we use the text() function to display the coordinates as text on the plot. This provides a visual representation of the coordinates for each point on the scatter plot − import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [2, 3, 5, 7, 11] plt.scatter(x, y) plt.xlabel(”X Axis”) plt.ylabel(”Y Axis”) plt.title(”Scatter Plot Coord Report”) plt.grid(True) # Displaying coordinates for i in range(len(x)): plt.text(x[i], y[i], f”({x[i]}, {y[i]})”, fontsize=8, verticalalignment=”bottom”) plt.show() Output Following is the output of the above code − Line Plot Coord Report In Matplotlib, a line plot coordinate report provides detailed information about the points plotted along a line in a line plot. This report includes the x and y coordinates of each point, indicating their positions on the plot. Additionally, it may contain other attributes such as markers, colors, or labels associated with each point. Example In here, we are creating a line plot using two sets of data: x and y, where x represents the values on the x-axis and y represents the corresponding values on the y-axis − import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [2, 3, 5, 7, 11] plt.plot(x, y) plt.xlabel(”X Axis”) plt.ylabel(”Y Axis”) plt.title(”Line Plot Coord Report”) plt.grid(True) # Display coordinates for i in range(len(x)): plt.text(x[i], y[i], f”({x[i]}, {y[i]})”, fontsize=8, verticalalignment=”bottom”) plt.show() Output On executing the above code we will get the following output − Bar Plot Coord Report In Matplotlib, a bar plot coordinate report provides detailed information about the bars displayed in a bar plot. This report includes the x and y coordinates of each bar, indicating their positions on the plot. Additionally, it may contain other attributes such as the width, height, or color of each bar. Example In the example below, we create a bar plot by first defining two sets of data: ”x” and ”y”. Then, we place a coordinate report on the plot using the text() function. This function specifies the coordinates (2, 7) with the label of the third data point ”C” and its corresponding value ”7”, formatted in red color and centered horizontally − import matplotlib.pyplot as plt # Sample data x = [”A”, ”B”, ”C”, ”D”, ”E”] y = [10, 15, 7, 10, 12] plt.bar(x, y) plt.xlabel(”X Axis”) plt.ylabel(”Y Axis”) plt.title(”Bar Plot Coord Report”) plt.grid(axis=”y”) # Coordinate report plt.text(2, 7, f”({x[2]}, {y[2]})”, fontsize=12, color=”red”, ha=”center”) plt.show() Output After executing the above code, we get the following output − Pie Chart Coord Report In Matplotlib, a pie chart coordinate report provides detailed information about the segments displayed in a pie chart. This report includes the position and size of each segment, represented as a fraction of the whole pie. Additionally, it may contain other attributes such as labels or colors associated with each segment. Example Now, we are creating a pie chart pie chart with labels and corresponding sizes. The “autopct” parameter formats the percentage values displayed on the chart. Additionally, we are placing a coordinate report at the center of the chart with coordinates (0, 0) − import matplotlib.pyplot as plt # Sample data labels = [”A”, ”B”, ”C”, ”D”, ”E”] sizes = [15, 30, 20, 10, 25] plt.pie(sizes, labels=labels, autopct=”%1.1f%%”, startangle=140) plt.axis(”equal”) plt.title(”Pie Chart Coord Report”) # Coordinate report plt.text(0, 0, f”(0.0, 0.0)”, fontsize=12, color=”yellow”, ha=”center”) plt.show() Output On executing the above code we will get the following output − Print Page Previous Next Advertisements ”;

Matplotlib – Viewlims

Matplotlib – Viewlims ”; Previous Next Viewlims or View limits, refer to the range of data that is displayed within a plot along the x and y axes. Viewlims are useful for interactive data visualization because they allow users to dynamically adjust the display of data. Matplotlib provides various methods and tools for setting and updating viewlims interactively, enabling users to explore and analyze data effectively. In general, view limits are automatically determined based on the data being plotted in matplotlib plots. This tutorial will see step by setp implementation of creating interactive zoom functionality in a Matplotlib plot with viewlims to create dynamic visualizations coresponding to the user interactions. Creating an Interactive Zoom Plot Create a class that regenerates a fractal set (the Mandelbrot set is a famous fractal in mathematics) as we zoom in, allowing us to observe increasing detail. Additionally, we”ll display a box in the left panel to show the area to which we are zoomed. This class defines the compute_image method to calculate the Mandelbrot set based on the provided bounds. And the axes_update method updates the plot based on the current view limits. It ensures that the Mandelbrot set is recalculated and redrawn whenever the view limits change. class InteractiveFractal: def __init__(self, h=500, w=500, niter=50, radius=2., power=2): self.height = h self.width = w self.niter = niter self.radius = radius self.power = power def compute_image(self, xstart, xend, ystart, yend): self.x = np.linspace(xstart, xend, self.width) self.y = np.linspace(ystart, yend, self.height).reshape(-1, 1) c = self.x + 1.0j * self.y threshold_time = np.zeros((self.height, self.width)) z = np.zeros(threshold_time.shape, dtype=complex) mask = np.ones(threshold_time.shape, dtype=bool) for i in range(self.niter): z[mask] = z[mask]**self.power + c[mask] mask = (np.abs(z) < self.radius) threshold_time += mask return threshold_time def axes_update(self, ax): ax.set_autoscale_on(False) self.width, self.height = np.round(ax.patch.get_window_extent().size).astype(int) vl = ax.viewLim extent = vl.x0, vl.x1, vl.y0, vl.y1 im = ax.images[-1] im.set_data(self.compute_image(*extent)) im.set_extent(extent) ax.figure.canvas.draw_idle() Updating View Limits We”ll create a class UpdateRectangle to create a rectangle that represents the area to which we are zoomed in the Mandelbrot set. This class extends the Rectangle class and is used to update the rectangle representing the zoom area as the view limits change. As we zoom in on the left panel, the rectangle will update its shape to match the bounds of the axes. class UpdateRectangle(Rectangle): def __call__(self, ax): self.set_bounds(*ax.viewLim.bounds) ax.figure.canvas.draw_idle() Connecting Callbacks Callbacks are connected to the xlim_changed and ylim_changed events of the second subplot (ax2). These callbacks trigger the update of the rectangle and the Mandelbrot set whenever the view limits change. # Connect for changing the view limits ax2.callbacks.connect(”xlim_changed”, rect) ax2.callbacks.connect(”ylim_changed”, rect) ax2.callbacks.connect(”xlim_changed”, md.ax_update) ax2.callbacks.connect(”ylim_changed”, md.ax_update) Here is the complete code The Mandelbrot set is initially plotted in two subplots (ax1 and ax2). The rectangle representing the zoom area is added to ax1, and callbacks are connected to ax2 to handle view limit changes. Example import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import Rectangle class UpdateRectangle(Rectangle): def __call__(self, ax): self.set_bounds(*ax.viewLim.bounds) ax.figure.canvas.draw_idle() class InteractiveFractal: def __init__(self, h=500, w=500, niter=50, radius=2., power=2): self.height = h self.width = w self.niter = niter self.radius = radius self.power = power def compute_image(self, xstart, xend, ystart, yend): self.x = np.linspace(xstart, xend, self.width) self.y = np.linspace(ystart, yend, self.height).reshape(-1, 1) c = self.x + 1.0j * self.y threshold_time = np.zeros((self.height, self.width)) z = np.zeros(threshold_time.shape, dtype=complex) mask = np.ones(threshold_time.shape, dtype=bool) for i in range(self.niter): z[mask] = z[mask]**self.power + c[mask] mask = (np.abs(z) < self.radius) threshold_time += mask return threshold_time def axes_update(self, ax): ax.set_autoscale_on(False) self.width, self.height = np.round(ax.patch.get_window_extent().size).astype(int) vl = ax.viewLim extent = vl.x0, vl.x1, vl.y0, vl.y1 im = ax.images[-1] im.set_data(self.compute_image(*extent)) im.set_extent(extent) ax.figure.canvas.draw_idle() md = InteractiveFractal() Z = md.compute_image(-2., 0.5, -1.25, 1.25) fig1, (ax1, ax2) = plt.subplots(1, 2, figsize=(7, 4)) ax1.imshow(Z, origin=”lower”, extent=(md.x.min(), md.x.max(), md.y.min(), md.y.max())) ax2.imshow(Z, origin=”lower”, extent=(md.x.min(), md.x.max(), md.y.min(), md.y.max())) rect = UpdateRectangle( [0, 0], 0, 0, facecolor=”none”, edgecolor=”black”, linewidth=1.0) rect.set_bounds(*ax2.viewLim.bounds) ax1.add_patch(rect) # Connect for changing the view limits ax2.callbacks.connect(”xlim_changed”, rect) ax2.callbacks.connect(”ylim_changed”, rect) ax2.callbacks.connect(”xlim_changed”, md.axes_update) ax2.callbacks.connect(”ylim_changed”, md.axes_update) ax2.set_title(“Zoom here”) plt.show() Output On executing the above program you will get the following output − Observe the below video to see how the viewlims works here − Print Page Previous Next Advertisements ”;

Matplotlib – Hyperlinks

Matplotlib – Hyperlinks ”; Previous Next A hyperlink, often referred to as a link, is a navigational element that present in various forms, such as text, images, icons, or buttons, within a document or on a webpage. When clicked or activated, a hyperlink redirects the user to a specified URL or resource, creating a seamless and interactive experience. Matplotlib provides a variety of tools to include hyperlinks in plots. In this tutorial, you will explore how to add hyperlinks in Matplotlib plots, such as SVG figures and PdfPages. Creating SVG figures with hyperlinks SVG (known as Scalable Vector Graphics) is an XML-based image format that supports hyperlinks. However, it”s crucial to note that hyperlinks in Matplotlib specifically apply to SVG output. If the plot is saved as a static image, such as PNG or JPEG, or is displayed as plot in a window, the hyperlink functionality will not be operational. In such case, you can use this feature in interactive plots with clickable elements. Example In this example, a scatter plot is created, and hyperlinks are assigned to individual data points using the set_urls method. import matplotlib.pyplot as plt import numpy as np fig = plt.figure() s = plt.scatter([1, 2, 3], [4, 5, 6]) s.set_urls([”https://www.tutorialspoint.com”, ”https://www.tutorialspoint.com/matplotlib/index.htm”, None]) fig.savefig(”scatter.svg”) Output After running the above code, you can check the output directory for the .svg image file. Adding Hyperlinks in PdfPages The PdfPages module in matplotlib enables the creation of multipage PDF documents. You can add hyperlinks to those pdf pages using the matplotlib text elements. Example In this example, a PDF document is created using PdfPages, and a text element with a hyperlink is added to the plot. import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages msr_line4 = r”$bf{” + ”Tutorialspoint Matplotlib Resource : ” + ”}$” + “https://www.tutorialspoint.com/matplotlib/index.htm” with PdfPages(”Adding_hyperlink_inside_a_PdfPage.pdf”) as pdf: plt.figure(figsize=(11, 8.5)) ax2 = plt.subplot2grid((9, 5), (1, 0), rowspan=1, colspan=2) ax2.text(0, 0, msr_line4, fontsize=9) plt.axis(”off”) pdf.savefig() plt.close Output After running the above code, you can check the output directory for the .pdf file. Hyperlinks in Interactive Plots For plots that are not rendered as SVG, such as interactive plots displayed in a Matplotlib window, hyperlinks can be implemented using event handlers. By creating a function to handle the “pick” event, you can define actions to be taken when specific elements, like data points, are clicked. Example The following example demonstrates how to open a specified hyperlink in a web browser when clicking on a data point. import matplotlib.pyplot as plt import webbrowser class CustomObject: def __init__(self, x, y, name): self.x = x self.y = y self.name = name def on_pick(event): webbrowser.open(”https://www.tutorialspoint.com”) # Create custom objects obj_a = CustomObject(0.1, 0.3, “Object A”) obj_b = CustomObject(0.2, 0.5, “Object B”) # Plotting objects with picker attribute fig, ax = plt.subplots() for obj in [obj_a, obj_b]: artist = ax.plot(obj.x, obj.y, ”ro”, picker=10)[0] artist.obj = obj # Connect pick event to the handler fig.canvas.callbacks.connect(”pick_event”, on_pick) plt.show() Output See the below video for how the output looks like. Print Page Previous Next Advertisements ”;

Matplotlib – Pie Chart

Matplotlib – Pie Chart ”; Previous Next A Pie Chart can only display one series of data. Pie charts show the size of items (called wedge) in one data series, proportional to the sum of the items. The data points in a pie chart are shown as a percentage of the whole pie. Matplotlib API has a pie() function that generates a pie diagram representing data in an array. The fractional area of each wedge is given by x/sum(x). If sum(x)< 1, then the values of x give the fractional area directly and the array will not be normalized. Theresulting pie will have an empty wedge of size 1 – sum(x). The pie chart looks best if the figure and axes are square, or the Axes aspect is equal. Parameters Following table lists down the parameters foe a pie chart − x array-like. The wedge sizes. labels list. A sequence of strings providing the labels for each wedge. Colors A sequence of matplotlibcolorargs through which the pie chart will cycle. If None, will use the colors in the currently active cycle. Autopct string, used to label the wedges with their numeric value. The label will be placed inside the wedge. The format string will be fmt%pct. Following code uses the pie() function to display the pie chart of the list of students enrolled for various computer language courses. The proportionate percentage is displayed inside the respective wedge with the help of autopct parameter which is set to %1.2f%. from matplotlib import pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.axis(”equal”) langs = [”C”, ”C++”, ”Java”, ”Python”, ”PHP”] students = [23,17,35,29,12] ax.pie(students, labels = langs,autopct=”%1.2f%%”) plt.show() Print Page Previous Next Advertisements ”;

Matplotlib – Scatter Plot

Matplotlib – Scatter Plot ”; Previous Next Scatter plots are used to plot data points on horizontal and vertical axis in the attempt to show how much one variable is affected by another. Each row in the data table is represented by a marker the position depends on its values in the columns set on the X and Y axes. A third variable can be set to correspond to the color or size of the markers, thus adding yet another dimension to the plot. The script below plots a scatter diagram of grades range vs grades of boys and girls in two different colors. import matplotlib.pyplot as plt girls_grades = [89, 90, 70, 89, 100, 80, 90, 100, 80, 34] boys_grades = [30, 29, 49, 48, 100, 48, 38, 45, 20, 30] grades_range = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] fig=plt.figure() ax=fig.add_axes([0,0,1,1]) ax.scatter(grades_range, girls_grades, color=”r”) ax.scatter(grades_range, boys_grades, color=”b”) ax.set_xlabel(”Grades Range”) ax.set_ylabel(”Grades Scored”) ax.set_title(”scatter plot”) plt.show() Print Page Previous Next Advertisements ”;

Matplotlib – Reverse Axes

Matplotlib – Reverse Axes ”; Previous Next What is Reverse Axes? In Matplotlib reverse axes refers to changing the direction of an axis, flipping it from its default orientation. This action alters the visual representation of the plot by reversing the order of the data along a specific axis usually the x-axis or y-axis. Reversing X-axis To reverse the x-axis in Matplotlib we can use the plt.gca().invert_xaxis() function. This method inverts the direction of the x-axis effectively flipping the plot horizontally. Data points that were originally plotted from left to right will now be displayed from right to left. Here is a detailed breakdown of how to reverse the x-axis: Steps to Reverse the X-axis The below are the steps to be followed to reverse the x-axis. Create a Plot Generate a plot with our data using Matplotlib. Example import matplotlib.pyplot as plt # Sample data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Plot with default axis orientation plt.plot(x, y, marker=”o”) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Default X-axis”) plt.show() Output Reverse the X-axis After creating the plot use plt.gca().invert_xaxis() to reverse the x-axis. Example import matplotlib.pyplot as plt # Sample data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Plot with default axis orientation plt.plot(x, y, marker=”o”) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Default X-axis”) plt.show() # Reversing the x-axis plt.plot(x, y, marker=”o”) plt.gca().invert_xaxis() # Reverse x-axis plt.xlabel(”Reversed X-axis”) plt.ylabel(”Y-axis”) plt.title(”Reversed X-axis”) plt.show() Output The second plot will display the same data as the first one but the x-axis will be reversed. Data points that were initially on the left side will now appear on the right side by altering the visual representation of the data. Use Cases for Reversing the X-axis Flipping Time Series Data − When we are plotting time series data then reversing the x-axis might better align with the chronological order. Reorienting Geographical Plots − In some geographical plots reversing the x-axis could match the expected orientation or conventions. Reversing the x-axis provides an alternative perspective for visualizing data allowing us to present information in a different order or orientation for clearer insights or better alignment with conventions. This function reverses the direction of the x-axis by flipping the plot horizontally. Data points that were originally plotted from left to right will now be displayed from right to left. Reversing Y-axis The plt.gca().invert_yaxis() function reverses the direction of the y-axis by flipping the plot vertically. Data points that were originally plotted from bottom to top will now be displayed from top to bottom. The reversing of Y – axis is also as same as the reversing the X – axis of a plot which we seen in the upper section. The below are the steps to be followed for reversing the Y – axis. Create a Plot Generate a plot with our data using Matplotlib. Example import matplotlib.pyplot as plt # Sample data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Plot with default axis orientation plt.plot(x, y, marker=”o”) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Default Y-axis”) plt.show() Output Reverse the Y-axis After creating the plot use plt.gca().invert_yaxis() to reverse the y-axis. Example import matplotlib.pyplot as plt # Sample data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Plot with default axis orientation plt.plot(x, y, marker=”o”) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Default Y-axis”) plt.show() # Reversing the x-axis # Reversing the y-axis plt.plot(x, y, marker=”o”) plt.gca().invert_yaxis() # Reverse y-axis plt.xlabel(”X-axis”) plt.ylabel(”Reversed Y-axis”) plt.title(”Reversed Y-axis”) plt.show() Output Print Page Previous Next Advertisements ”;

Matplotlib – Subplots() Function

Matplotlib – Subplots() Function ”; Previous Next Matplotlib’spyplot API has a convenience function called subplots() which acts as a utility wrapper and helps in creating common layouts of subplots, including the enclosing figure object, in a single call. Plt.subplots(nrows, ncols) The two integer arguments to this function specify the number of rows and columns of the subplot grid. The function returns a figure object and a tuple containing axes objects equal to nrows*ncols. Each axes object is accessible by its index. Here we create a subplot of 2 rows by 2 columns and display 4 different plots in each subplot. import matplotlib.pyplot as plt fig,a = plt.subplots(2,2) import numpy as np x = np.arange(1,5) a[0][0].plot(x,x*x) a[0][0].set_title(”square”) a[0][1].plot(x,np.sqrt(x)) a[0][1].set_title(”square root”) a[1][0].plot(x,np.exp(x)) a[1][0].set_title(”exp”) a[1][1].plot(x,np.log10(x)) a[1][1].set_title(”log”) plt.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

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 ”;