Matplotlib – LaTeX for Mathematical Expressions ”; Previous Next What is Rendering mathematical expressions? Rendering mathematical expressions in LaTeX involves using LaTeX syntax to write mathematical equations, symbols and formulas. LaTeX provides a comprehensive set of commands and notation to create complex mathematical expressions with precision and clarity. Importance of LaTeX for Mathematics Precision and Clarity − LaTeX allows precise typesetting of mathematical notation and symbols. Consistency − Maintains consistency in formatting across mathematical documents. Publication-Quality − Produces high-quality mathematical expressions suitable for academic and scientific publications. LaTeX”s support for mathematical typesetting makes it a preferred choice for researchers, mathematicians, scientists and academics when writing technical or mathematical documents that require accurate and well-formatted mathematical notation. LaTeX for Mathematical Expressions The below are the components of LaTex in Mathematical Expressions. Inline Math Mode Inline math mode in LaTeX is used to include mathematical expressions within the text of a document. We can use inline math mode by enclosing the mathematical expression between a pair of single dollar signs $…$. Using the inline math mode In this example the mathematical expression `frac{-b pm sqrt{b^2 – 4ac}}{2a}` is included within the text using inline math mode. The result is that the mathematical expression is rendered within the line of text. Example The quadratic formula is given by $x = frac{-b pm sqrt{b^2 – 4ac}}{2a}$. Output On executing the above code you will get the following output − Display Math Mode Display math mode in LaTeX is used to showcase mathematical expressions in a separate block, centered and distinct from the surrounding text. It”s commonly used for larger or standalone equations that deserve prominence in a document. To use display math mode in LaTeX we have several options let’s see them one by one. Double Dollar Sign `$$…$$` Enclose the mathematical expression between $$ symbols for displayed equations. Example In this example we are displaying the given input equation by using the $$..$$. $$ f(x) = int_{a}^{b} g(x) , dx $$ Output On executing the above code you will get the following output − ‘equation’ Environment Use the `equation` environment to create a numbered equation. Example begin{equation} f(x) = int_{a}^{b} g(x) , dx end{equation} Output On executing the above code you will get the following output − Symbols and Operators In LaTeX we can use a wide range of symbols and operators to represent mathematical notation, expressions and operations. Here are some commonly used symbols and operators along with their LaTeX commands. Greek Letters − Alpha: `alpha`, Beta: `beta`, Gamma: `gamma`, Delta: `delta` and so on. Arithmetic Operators − Plus: `+`, Minus: `-`, Multiplication: `times` or `*`, Division: `div` or `/` Relations and Comparisons − Equals: `=`, Not equals: `neq`, Less than: `<`, Greater than: `>` and so on. Set Theory − Union: `cup`, Intersection: `cap`, Subset: `subset`, Superset: `supset` and so on Calculus and Limits − Integral: `int`, Summation: `sum`, Limit: `lim`, Derivative: `frac{dy}{dx}` Functions − Sine: `sin`, Cosine: `cos`, Tangent: `tan`, Logarithm: `log`, Exponential: `exp` Roots and Exponents − Square root: `sqrt{x}`, Exponent: `x^2`, Subscript: `x_1`, Superscript: `x^i` Other Notations Fractions − `frac{numerator}{denominator}` Matrices − `bmatrix`, `pmatrix`, `vmatrix`, etc., using the `amsmath` package Special Symbols − For example, `infty` for infinity, `emptyset` for an empty set, etc. Example In this example we are using the $$..$$, to display the symbols and operators in the LaTex of matplotlib library. $$(alpha + beta = gamma times delta)$$ Output On executing the above code you will get the following output − By utilizing these LaTeX commands for symbols and operators we can create complex mathematical expressions with precision and clarity in our LaTeX documents. Fraction and Subscript/Superscript In LaTeX we can easily create fractions, subscripts and superscripts to represent mathematical expressions using specific commands and notation. Fractions To create fractions we can use the `frac{numerator}{denominator}` command. Example In this example we are creating the fraction ¾. The fraction is $frac{3}{4}$. Output On executing the above code you will get the following output − Subscripts and Superscripts Subscripts and superscripts can be added using the ‘_’ for subscripts and ‘^’ for superscripts. Example In this example we are displaying a script content. $x_i^2$ denotes $x$ raised to the power of $i$ squared. Output On executing the above code you will get the following output − Nested Subscripts and Superscripts We can also nest subscripts and superscripts by enclosing the content in curly braces {}. Example In this example we are displaying the nested subscripts. $x_{i_j}^{2k}$ represents a nested subscript and superscript. Output On executing the above code you will get the following output − Using Commands For more complex expressions or to ensure consistent formatting we can use commands such as subscript{} and superscript{} provided by packages like fixltx2e. Example In this example we are displaying the complex expressions. $x subscript{i} superscript{2}$ Output On executing the above code you will get the following output − LaTeX offers straightforward ways to create fractions, subscripts and superscripts, allowing us to represent mathematical expressions accurately and efficiently. Matrices and Arrays In LaTeX matrices and arrays are used to represent data in matrix form or to display sets of equations. The array environment is the basic structure for creating matrices and arrays in LaTeX while the matrix environments provided by the amsmath package offer additional functionality and easier syntax for matrices. Creating Matrices and Arrays Here are we
Category: matplotlib
Matplotlib – Text properties
Matplotlib – Text properties ”; Previous Next Text properties in Matplotlib refer to a set of attributes that can be configured to control the appearance and layout of text elements within a plot. These properties include various characteristics such as − font style color size alignment, and more. By manipulating these properties, you can customize the visual aspects of text within the plots. Controlling text properties and layout in Matplotlib involves configuring various attributes of the matplotlib.text.Text instances. These properties can be adjusted through keyword arguments in functions like set_title, set_xlabel, and text. Below, we explore key text properties in Matplotlib along with examples. Text layout and positioning properties Text layout and positioning are crucial aspects for placing and aligning text elements within a plot. Following are the list of properties and their details. Position − Specifies the coordinates (x, y) where the text is placed. Rotation − Defines the angle of rotation for the text. Options include degrees, ”vertical”, or ”horizontal”. Horizontal Alignment (ha) − Determines the alignment of the text along the x-axis. Options include ”center”, ”right”, and ”left”. Vertical Alignment (va) − Controls the alignment of the text along the y-axis. Options include ”center”, ”top”, ”bottom”, and ”baseline”. Multialignment − For newline-separated strings, this property controls left, center, or right justification for different lines. Example This example demonstrates the application of various layout and positioning properties. import matplotlib.pyplot as plt # Create a figure fig, ax = plt.subplots(figsize=(7, 4)) # Set the axis limits plt.axis((0, 10, 0, 10)) # Add text with various layout and positioning properties ax.text(5, 7, ”Centered Text with 0 rotation”, horizontalalignment=”center”, verticalalignment=”center”, rotation=0) ax.text(1, 5, ”Right Aligned Text with 90 degrees rotation”, ha=”right”, va=”center”, rotation=90) ax.text(9, 5, ”Left Aligned Text with -90 degrees rotation”, ha=”left”, va=”center”, rotation=-90) ax.text(5, 2, ”MultilinenText”, ha=”center”, va=”center”, multialignment=”center”) # Display the plot plt.show() print(”Text is added successfully with the various layout and positioning properties..”) Output On executing the above code we will get the following output − Text is added successfully with the various layout and positioning properties.. Text color and transparency properties Color and transparency properties enhance the visual appearance of text elements within a plot. color − Specifies the color of the text. This can be any valid matplotlib color. backgroundcolor − Defines the background color behind the text. It can be set using any valid matplotlib color. alpha − Represents the transparency of the text. It is specified as a float, where 0.0 is fully transparent, and 1.0 is fully opaque. Example This example demonstrates how to use color and transparency properties in Matplotlib. import matplotlib.pyplot as plt # Create a figure fig, ax = plt.subplots(figsize=(7, 4)) # Set the axis limits plt.axis((0, 10, 0, 10)) # Add text with color and transparency properties ax.text(3, 8, ”Plain text without any property”) ax.text(3, 6, ”Colored Text”, color=”blue”) ax.text(3, 4, ”Background Color”, backgroundcolor=”yellow”) ax.text(3, 2, ”Transparent Text”, alpha=0.5) # Display the plot plt.show() print(”Text added successfully…”) Output On executing the above code we will get the following output − Text added successfully… Different font properties Font properties are essential for customizing the appearance of text elements within a plot. These properties provide control over the type, style, thickness, size, variant, and name of the font used for rendering text. Family − Specifies the type of font to be used, such as ”serif”, ”sans-serif”, or ”monospace”. Style or Fontstyle − Determines the style of the font, with options like ”normal”, ”italic”, or ”oblique”. Weight or Fontweight − The thickness or boldness of the font. Options include ”normal”, ”bold”, ”heavy”, ”light”, ”ultrabold”, and ”ultralight”. Size or Fontsize − Specifies the size of the font in points or relative sizes like ”smaller” or ”x-large”. Name or Fontname − Defines the name of the font as a string. Examples include ”Sans”, ”Courier”, ”Helvetica”, and more. Variant − Describes the font variant, with options like ”normal” or ”small-caps”. Example This example demonstrates how to use various font properties to customize the appearance of text in Matplotlib. import matplotlib.pyplot as plt # Create a figure fig = plt.figure(figsize=(7, 4)) # Set the axis limits plt.axis((0, 10, 0, 10)) # Define a long string sample_text = (“Tutorialspoint”) # Add text at various locations with various configurations plt.text(0, 9, ”Oblique text placed at the center with a 25-degree rotation”, fontstyle=”oblique”, fontweight=”heavy”, ha=”center”, va=”baseline”, rotation=45, wrap=True) plt.text(7.5, 0.5, ”Text placed at the left with a 45-degree rotation”, ha=”left”, rotation=45, wrap=True) plt.text(5, 5, sample_text + ”nMiddle”, ha=”center”, va=”center”, color=”green”, fontsize=24) plt.text(10.5, 7, ”Text placed at the right with a -45-degree rotation”, ha=”right”, rotation=-45, wrap=True) plt.text(5, 10, ”Sans text with oblique style is placed at the center”, fontsize=10, fontname=”Sans”, style=”oblique”, ha=”center”, va=”baseline”, wrap=True) plt.text(6, 3, ”A serif family text is placed right with the italic style”, family=”serif”, style=”italic”, ha=”right”, wrap=True) plt.text(-0.5, 0, ”Small-caps variant text is placed at the left with a -25-degree rotation”, variant=”small-caps”, ha=”left”, rotation=-25, wrap=True) # Display the plot plt.show() print(”Text added successfully…”) Output On executing the above code we will get the following output − Text added successfully… The bounding box and Clipping Properties Bounding box and Clipping properties are used to control the layout and visibility of text elements within a plot. These properties include specifying a bounding box for text, defining clipping parameters, and enabling or disabling clipping. Bbox − Defines a bounding box for the text. It includes properties like color, padding, and more. Clip Box and Clip Path − Specify a bounding box or path for clipping the text. These
Matplotlib – Styling with Cycler ”; Previous Next Cycler is a separate package that is extracted from Matplotlib, and it is designed to control the style properties like color, marker, and linestyle of the plots. This tool allows you to easily cycle through different styles for plotting multiple lines on a single axis. Importing the Cycler − To start using Cycler, you need to import it into your Python script. from cycler import cycler This enables you to create and manipulate Cyclers for styling your plots. Creating a Cycler − The cycler function is used to create a new Cycler object. It can be called with a single positional argument, a pair of positional arguments, or a combination of keyword arguments. # Creating a color Cycler color_cycle = cycler(color=[”r”, ”g”, ”b”]) The “color_cycle” is a Cycler object that cycles through the colors red, green, and blue. Once you have a Cycler, you can link it to the matplotlib’s plot attribute. Cycling Through Multiple Properties The Cycler package provides advanced operations for combining and manipulating multiple Cyclers to create complex style variations. It means that you can add cyclers together or multiply them to combine different properties. Following are the different operations in cycler − Cycler Addition − Multiple Cycler objects can be combined using the + operator. For example − cycler(color=[”r”, ”g”, ”b”]) + cycler(linestyle=[”-”, ”–”, ”:”]) Cycler Multiplication − Cyclers can be multiplied to create a wider range of unique styles. For example: cycler(color=[”r”, ”g”, ”b”]) * cycler(linestyle=[”-”, ”–”, ”:”]) Integer Multiplication − Cycler objects can be multiplied by integer values to increase their length. Both cycler * 2 and 2 * cycler yield the same result, repeating the elements. Here is the syntax: color_cycle * 2 Cycler Concatenation − Cycler objects can be concatenated using the Cycler.concat() method or the top-level concat() function. In this tutorial, we will explore two distinct approaches for customizing the style of plots in Matplotlib using the Cycler package. Setting Default Property Cycle (rc parameter) − This is the global setting that ensures that every subsequent plot will be set to the specified style. Setting Property Cycle for a Single Pair of Axes − This is the local setting that applies a custom property cycle exclusively to a particular set of axes. Setting Default Property Cycle (rc parameter) In matplotlib, specifying a default style for all future plots will be possible by using matplotlib.pyplot.rc() method, this will set the default cycler for lines in your plots and axes. This means every plot you make in the future will follow this color and linestyle cycle unless you override it. Example 1 This is a basic example that demonstrates how to cycle through different line styles for multiple plots. Here the plt.rc() method is used to set the default linestyle for the plot. import matplotlib.pyplot as plt from cycler import cycler # Set the property cycle for the linestyle of lines in the axes linestyle_cycler = cycler(”linestyle”, [”-”, ”:”, ”-.”]) plt.rc(”axes”, prop_cycle=linestyle_cycler) # Create multiple plots using a loop for i in range(5): x = range(i, i + 5) plt.plot(range(5), x) # Display the plot plt.legend([”first”, ”second”, ”third”, ”fourth”, ”fifth”], loc=”upper left”, fancybox=True, shadow=True) plt.show() Output On executing the above code we will get the following output − Let’s combine multiple (color and a linestyle) cyclers together by adding (+) symbol to them. Example 2 This example demonstrates how to define a default style (cycle through both colors and linestyles) for your plots using Cycler, making it easy to visualize all plots with different colors (”r”, ”g”, ”b”, ”y”) and linestyles (”-”, ”–”, ”:”, ”-.”). from cycler import cycler import matplotlib.pyplot as plt import numpy as np # Generate sample data x = np.linspace(0, 2 * np.pi, 50) offsets = np.linspace(0, 2 * np.pi, 4, endpoint=False) yy = np.transpose([np.sin(x + phi) for phi in offsets]) # Set default prop_cycle default_cycler = (cycler(color=[”r”, ”g”, ”b”, ”y”]) + cycler(linestyle=[”-”, ”–”, ”:”, ”-.”])) plt.rc(”lines”, linewidth=4) plt.rc(”axes”, prop_cycle=default_cycler) # Plot with the default color cycle plt.plot(yy) plt.title(”Set Default Color Cycle”) plt.show() Output On executing the above code we will get the following output − Setting Property Cycle for a Single Pair of Axes Customize the style for a specific pair of axes within a figure without affecting others. you use the matplotlib.axes.Axes.set_prop_cycle() to apply this custom cycler. This means that only the plots on this particular set of axes will follow the specified color and linewidth cycle. Example In this example, the first set of plots on ax0 follows the default color and linestyle cycle. The second set of plots on ax1 uses a custom color and linewidth cycle defined specifically for this axis using the set_prop_cycle() method. from cycler import cycler import matplotlib.pyplot as plt import numpy as np # Generate sample data x = np.linspace(0, 2 * np.pi, 50) offsets = np.linspace(0, 2 * np.pi, 4, endpoint=False) yy = np.transpose([np.sin(x + phi) for phi in offsets]) # Define a default cycler for colors and linestyles default_cycler = (cycler(color=[”r”, ”g”, ”b”, ”y”]) + cycler(linestyle=[”-”, ”–”, ”:”, ”-.”])) # Set the default linewidth for lines in all plots plt.rc(”lines”, linewidth=4) # Set the default property cycle for axes to the default cycler plt.rc(”axes”, prop_cycle=default_cycler) # Create a figure and two axes fig, (ax0, ax1) = plt.subplots(nrows=2, figsize=(7, 8)) # Plot on the first axis using the default color cycle ax0.plot(yy) ax0.set_title(”Default Color Cycle: rgby”) # Define a custom cycler custom_cycler = (cycler(color=[”c”, ”m”, ”y”, ”k”]) + cycler(lw=[1, 2, 3, 4])) # Set the
Matplotlib – Colormaps
Matplotlib – Colormaps ”; Previous Next Colormap (often called a color table or a palette), is a set of colors arranged in a specific order, it is used to visually represent data. See the below image for reference − In the context of Matplotlib, colormaps play a crucial role in mapping numerical values to colors in various plots. Matplotlib offers built-in colormaps and external libraries like Palettable, or even it allows us to create and manipulate our own colormaps. Colormaps in Matplotlib Matplotlib provides number of built-in colormaps like ”viridis” or ”copper”, those can be accessed through matplotlib.colormaps container. It is an universal registry instance, which returns a colormap object. Example Following is the example that gets the list of all registered colormaps in matplotlib. from matplotlib import colormaps print(list(colormaps)) Output [”magma”, ”inferno”, ”plasma”, ”viridis”, ”cividis”, ”twilight”, ”twilight_shifted”, ”turbo”, ”Blues”, ”BrBG”, ”BuGn”, ”BuPu”, ”CMRmap”, ”GnBu”, ”Greens”, ”Greys”, ”OrRd”, ”Oranges”, ”PRGn”, ”PiYG”, ”PuBu”, ”PuBuGn”, ”PuOr”, ”PuRd”, ”Purples”, ”RdBu”, ”RdGy”, ”RdPu”, ”RdYlBu”, ”RdYlGn”, ”Reds”, ”Spectral”, ”Wistia”, ”YlGn”, ”YlGnBu”, ”YlOrBr”, ”YlOrRd”, ”afmhot”, ”autumn”, ”binary”, ”bone”, ”brg”, ”bwr”, ”cool”, ”coolwarm”, ”copper”, ”cubehelix”, ”flag”, ”gist_earth”, ”gist_gray”, ”gist_heat”, ”gist_ncar”, ”gist_rainbow”, ”gist_stern”, ”gist_yarg”, ”gnuplot”, ”gnuplot2”, ”gray”, ”hot”, ”hsv”, ”jet”, ”nipy_spectral”, ”ocean”, …] Accessing Colormaps and their Values You can get a named colormap using matplotlib.colormaps[”viridis”], and it returns a colormap object. After obtaining a colormap object, you can access its values by resampling the colormap. In this case, viridis is a colormap object, when passed a float between 0 and 1, it returns an RGBA value from the colormap. Example Here is an example that accessing the colormap values. import matplotlib viridis = matplotlib.colormaps[”viridis”].resampled(8) print(viridis(0.37)) Output (0.212395, 0.359683, 0.55171, 1.0) Creating and Manipulating Colormaps Matplotlib provides the flexibility to create or manipulate your own colormaps. This process involves using the classes ListedColormap or LinearSegmentedColormap. Creating Colormaps with ListedColormap The ListedColormaps class is useful for creating custom colormaps by providing a list or array of color specifications. You can use this to build a new colormap using color names or RGB values. Example The following example demonstrates how to create custom colormaps using the ListedColormap class with specific color names. import matplotlib as mpl from matplotlib.colors import ListedColormap import matplotlib.pyplot as plt import numpy as np # Creating a ListedColormap from color names colormaps = [ListedColormap([”rosybrown”, ”gold”, “crimson”, “linen”])] # Plotting examples np.random.seed(19680801) data = np.random.randn(30, 30) n = len(colormaps) fig, axs = plt.subplots(1, n, figsize=(7, 3), layout=”constrained”, squeeze=False) for [ax, cmap] in zip(axs.flat, colormaps): psm = ax.pcolormesh(data, cmap=cmap, rasterized=True, vmin=-4, vmax=4) fig.colorbar(psm, ax=ax) plt.show() Output On executing the above program, you will get the following output − Creating Colormaps with LinearSegmentedColormap The LinearSegmentedColormap class allows more control by specifying anchor points and their corresponding colors. This enables the creation of colormaps with interpolated values. Example The following example demonstrates how to create custom colormaps using the LinearSegmentedColormap class with a specific list of color names. import matplotlib as mpl from matplotlib.colors import LinearSegmentedColormap import matplotlib.pyplot as plt import numpy as np # Creating a LinearSegmentedColormap from a list colors = [“rosybrown”, “gold”, “lawngreen”, “linen”] cmap_from_list = [LinearSegmentedColormap.from_list(“SmoothCmap”, colors)] # Plotting examples np.random.seed(19680801) data = np.random.randn(30, 30) n = len(cmap_from_list) fig, axs = plt.subplots(1, n, figsize=(7, 3), layout=”constrained”, squeeze=False) for [ax, cmap] in zip(axs.flat, cmap_from_list): psm = ax.pcolormesh(data, cmap=cmap, rasterized=True, vmin=-4, vmax=4) fig.colorbar(psm, ax=ax) plt.show() Output On executing the above program, you will get the following output − Reversing Colormaps Reversing a colormap can be done by using the colormap.reversed() method. This creates a new colormap that is the reversed version of the original colormap. Example This example generates side-by-side visualizations of the original colormap and its reversed version. from matplotlib.colors import ListedColormap import matplotlib.pyplot as plt import numpy as np # Define a list of color values in hexadecimal format colors = [“#bbffcc”, “#a1fab4”, “#41b6c4”, “#2c7fb8”, “#25abf4″] # Create a ListedColormap with the specified colors my_cmap = ListedColormap(colors, name=”my_cmap”) # Create a reversed version of the colormap my_cmap_r = my_cmap.reversed() # Define a helper function to plot data with associated colormap def plot_examples(colormaps): np.random.seed(19680801) data = np.random.randn(30, 30) n = len(colormaps) fig, axs = plt.subplots(1, n, figsize=(n * 2 + 2, 3), layout=”constrained”, squeeze=False) for [ax, cmap] in zip(axs.flat, colormaps): psm = ax.pcolormesh(data, cmap=cmap, rasterized=True, vmin=-4, vmax=4) fig.colorbar(psm, ax=ax) plt.show() # Plot the original and reversed colormaps plot_examples([my_cmap, my_cmap_r]) Output On executing the above program, you will get the following output − Changing the default colormap To change the default colormap for all subsequent plots, you can use mpl.rc() to modify the default colormap setting. Example Here is an example that changes the default colormap to RdYlBu_r by modifying the global Matplotlib settings like mpl.rc(”image”, cmap=”RdYlBu_r”). import numpy as np from matplotlib import pyplot as plt import matplotlib as mpl # Generate random data data = np.random.rand(4, 4) # Create a figure with two subplots fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(7, 4)) # Plot the first subplot with the default colormap ax1.imshow(data) ax1.set_title(“Default colormap”) # Set the default colormap globally to ”RdYlBu_r” mpl.rc(”image”, cmap=”RdYlBu_r”) # Plot the modified default colormap ax2.imshow(data) ax2.set_title(“Modified default colormap”) # Display the figure with both subplots plt.show() Output On executing the above code we will get the following output − Plotting Lines with Colors through Colormap To plot multiple lines with different colors through a colormap, you can utilize Matplotlib”s plot() function along with a colormap to assign different colors to each line. Example The following example plot multiple lines by iterating over a range and plotting each line
Matplotlib – Images
Matplotlib – Images ”; Previous Next What are Images in Matplotlib? In Matplotlib library displaying and manipulating images involves using the imshow() function. This function visualizes 2D arrays or images. This function is particularly useful for showing images in various formats such as arrays representing pixel values or actual image files. Images in Matplotlib provide a way to visualize gridded data, facilitating the interpretation and analysis of information represented in 2D arrays. This capability is crucial for various scientific, engineering and machine learning applications that deal with image data. Use Cases for Images in Matplotlib The following are the use cases of Images in Matplotlib library. Visualizing Gridded Data The matplotlib library can be used for displaying scientific data such as heatmaps, terrain maps, satellite images etc. Image Processing Analyzing and manipulating image data in applications such as computer vision or image recognition. Artificial Intelligence and Machine Learning Handling and processing image data in training and evaluation of models. Loading and Displaying Images To load and display an image using Matplotlib library we can use the following lines of code. Example import matplotlib.pyplot as plt import matplotlib.image as mpimg # Load the image img = mpimg.imread(”Images/flowers.jpg”) # Load image file # Display the image plt.imshow(img) plt.axis(”off”) # Turn off axis labels and ticks (optional) plt.show() Key Points of the above code matplotlib.image.imread() − Loads an image file and returns it as an array. The file path (”image_path”) should be specified. plt.imshow() − Displays the image represented by the array. plt.axis(”off”) − Turns off axis labels and ticks, which is optional for purely displaying the image without axes. Output Customizing Image Display We can customize the image as per the requirement by thebelow mentioned functions. Colormap − We can apply a colormap to enhance image visualization by specifying the cmap parameter in imshow(). Colorbar − To add a colorbar indicating the intensity mapping we can use plt.colorbar() after imshow(). Example import matplotlib.pyplot as plt import matplotlib.image as mpimg # Load the image img = mpimg.imread(”Images/flowers.jpg”) # Load image file # Display the image plt.imshow(img, cmap = ”Oranges”) plt.colorbar() # Turn on axis labels and ticks (optional) plt.axis(”on”) plt.show() Output Image Manipulation We can perform manipulation for our images by using the below mentioned functions. Cropping − Select a specific portion of the image by slicing the array before passing it to imshow(). Resizing − Use various image processing libraries such as Pillow, OpenCV to resize images before displaying them. Example In this example we are manipulating the image and displaying the image by using the above mentioned functions. import matplotlib.pyplot as plt import matplotlib.image as mpimg import cv2 # Load the image img = mpimg.imread(”Images/flowers.jpg”) # Display the image with grayscale colormap and colorbar plt.imshow(img, cmap=”gray”) plt.colorbar() # Display only a portion of the image (cropping) plt.imshow(img[100:300, 200:400]) # Display a resized version of the image resized_img = cv2.resize(img, (new_width, new_height)) plt.imshow(resized_img) plt.show() Output Remember Matplotlib”s imshow() is suitable for basic image display and visualization. For more advanced image processing tasks such as resizing, filtering, etc. using dedicated image processing libraries like OpenCV or Pillow is recommended. Print Page Previous Next Advertisements ”;
Matplotlib – Paths
Matplotlib – Paths ”; Previous Next A path is a route (track) that guides movement from one place to another. It can be physical, like a trail or road, or abstract, like a series of steps to achieve a goal. Paths provide direction and help us to navigate through spaces. They signify a way to reach a destination. Paths in Matplotlib In Matplotlib, paths are fundamental objects used to draw shapes and lines on plots. A path consists of a series of connected points, known as vertices or nodes, along with instructions on how to connect these points to form shapes like lines, curves, or polygons. You can create a path in Matplotlib using the “Path” class. These paths can be used to create various types of plots such as lines, curves, polygons, and even custom shapes. Paths provide a way to define the appearance of objects in plots, allowing you to control their size, position, and style. Let’s start by drawing a basic straight line path. Straight Line Path In Matplotlib, a straight line path refers to a basic geometric element consisting of two points connected by a straight line. This path is created by specifying the coordinates of the starting point (often called the “origin”) and the ending point of the line. Matplotlib then draws a straight line between these two points, forming the path. Example In the following example, we are creating a straight line path using the Path class in Matplotlib. We define two vertices representing the starting and ending points of the line. Additionally, we specify the path codes to indicate that the path moves to the first vertex and then creates a line to the second vertex. By constructing the path using these vertices and codes, we achieve the representation of a straight line − import matplotlib.pyplot as plt from matplotlib.path import Path import matplotlib.patches as patches # Defining the vertices for the straight line path verts = [ # Starting point (0, 0), # Ending point (1, 1) ] # Defining the codes for the straight line path codes = [Path.MOVETO, Path.LINETO] # Creating the straight line path path = Path(verts, codes) # Plotting the path fig, ax = plt.subplots() patch = patches.PathPatch(path, facecolor=”none”, lw=2) ax.add_patch(patch) ax.set_title(”Straight Line Path”) ax.set_xlim(0, 1) ax.set_ylim(0, 1) ax.set_xlabel(”X-axis”) ax.set_ylabel(”Y-axis”) ax.grid(True) plt.show() Output Following is the output of the above code − Circle Path In Matplotlib, a circle path represents a circular shape drawn on a plot. It is created by specifying the center point of the circle and its radius. Matplotlib then generates a series of points around the circumference of the circle, connecting them to form a closed path. Example In here, we are creating a circular path using the Path class in Matplotlib. We generate a sequence of vertices along the circumference of a circle by defining angles uniformly spaced around the unit circle. Using trigonometric functions, we compute the coordinates of these vertices. Subsequently, we define the path codes to connect these vertices with lines − import matplotlib.pyplot as plt from matplotlib.path import Path import matplotlib.patches as patches import numpy as np # Defining the angles for the circle path theta = np.linspace(0, 2*np.pi, 100) # Defining the vertices for the circle path verts = np.column_stack([np.cos(theta), np.sin(theta)]) # Definng the codes for the circle path codes = [Path.MOVETO] + [Path.LINETO] * (len(verts) – 1) # Creating the circle path path = Path(verts, codes) # Plotting the path fig, ax = plt.subplots() patch = patches.PathPatch(path, facecolor=”none”, lw=2) ax.add_patch(patch) ax.set_title(”Circle Path”) ax.set_xlim(-1.1, 1.1) ax.set_ylim(-1.1, 1.1) ax.set_xlabel(”X-axis”) ax.set_ylabel(”Y-axis”) ax.grid(True) plt.show() Output On executing the above code we will get the following output − Bezier Curve Path In Matplotlib, a Bezier curve path is a smooth, curved line created using control points to define its shape. To construct a Bezier curve, you specify a series of control points that guide the curve”s path. These control points determine the curve”s direction and shape, allowing you to create smooth, flowing shapes. Matplotlib then generates the curve by connecting the dots these control points. Example Now, we are creating a Bezier curve path in Matplotlib using the Path class. We specify the control points that define the shape of the Bezier curve. Additionally, we define the path codes to indicate the type of curve segments between consecutive control points. By constructing the path with these control points and codes, we create a smooth Bezier curve − import matplotlib.pyplot as plt from matplotlib.path import Path import matplotlib.patches as patches # Defining the control points for the Bezier curve verts = [ (0.1, 0.1), (0.2, 0.8), (0.8, 0.8), (0.9, 0.1), ] # Defining the codes for the Bezier curve path codes = [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4] # Creating the Bezier curve path path = Path(verts, codes) # Plotting the path fig, ax = plt.subplots() patch = patches.PathPatch(path, facecolor=”none”, lw=2) ax.add_patch(patch) ax.set_title(”Bezier Curve Path”) ax.set_xlim(0, 1) ax.set_ylim(0, 1) ax.set_xlabel(”X-axis”) ax.set_ylabel(”Y-axis”) ax.grid(True) plt.show() Output After executing the above code, we get the following output − Polygon Path In Matplotlib, a polygon path represents a closed shape with multiple straight sides, similar to a geometric polygon. This shape is created by specifying the coordinates of its vertices, or corner points, in a specific order. Matplotlib then connects these points sequentially to form the edges of the polygon and closes the path by connecting the last point to the first. Polygon paths are versatile elements used to represent various shapes, such as triangles, rectangles, pentagons, or any other multi-sided figures. They can be filled with color to represent areas or used as outlines to highlight specific regions in plots. Example In this example, we create a polygonal path
Matplotlib – Basic Units
Matplotlib – Basic Units ”; Previous Next What are Basic Units? In Matplotlib basic units refer to the fundamental elements used to define and measure various aspects of a plot such as length, width, positions and coordinates. Understanding these units is crucial for accurately placing elements within a plot and controlling its overall layout. Common Basic Units in Matplotlib The following are the common basic units available in matplotlib library. Points (pt) In Matplotlib points typically refer to a unit of measurement used for specifying various visual properties within a plot such as line widths, marker sizes and text sizes. The point (pt) is a standard unit in typography and graphics often used for its device-independent size representation. Usage of Points in Matplotlib Line Widths − The linewidth parameter in Matplotlib functions such as plt.plot() allows us to specify the width of lines in points. Text Sizes − The fontsize parameter in Matplotlib functions plt.xlabel(), plt.ylabel(), plt.title() enables setting the size of text in points. Marker Sizes − The markersize parameter in plot functions such as plt.plot() defines the size of markers in points. Figure Size − When specifying the figure size using plt.figure(figsize=(width, height)) the dimensions are in inches. However the default size might differ across systems such as 1 inch might not always equal 72 points but this is the typical convention. Converting Points to Other Units Matplotlib works internally with points but when setting figure sizes or dimensions it”s common to use inches. As a reference 1 inch is approximately equal to 72 points. 1 inch = 72 points 1 point ≈ 0.01389 inches Understanding and utilizing points as a unit of measurement in Matplotlib allows for precise control over the visual properties of elements within plots ensuring the desired appearance and readability. Example In this example we are setting the line width in points for the line plot. import matplotlib.pyplot as plt plt.figure(figsize=(6, 4)) # 6 inches wide, 4 inches tall plt.plot([1, 2, 3], [4, 5, 6], linewidth=3.5) # Line width in points plt.xlabel(”X-axis”, fontsize=12) # Text size in points plt.ylabel(”Y-axis”, fontsize=12) plt.show() Output Following is the output of the above code − Inches (in) Inches are used to specify the overall size of a figure or subplots in Matplotlib. For example figsize = (width, height) in inches defines the width and height of a figure. Example In this example we are specifying the size of figure in inches. import matplotlib.pyplot as plt plt.figure(figsize=(4, 4)) # 6 inches wide, 4 inches tall plt.plot([1, 2, 3], [4, 5, 6]) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Example Plot with 4×4 Inches”) plt.show() Output Following is the output of the above code − Conversion The conversion factor between inches and other units commonly used in Matplotlib: 1 inch ≈ 2.54 centimeters Data Units Data units represent the actual values plotted along the x-axes and y-axes. Matplotlib uses these units to plot data points on the graph. The conversion from data units to physical units on the plot is determined by the axis scales such as linear, logarithmic etc. Key Points about Data Units in Matplotlib Numerical Data − Data units represent the numeric values that we plot along the x-axis and y-axis. Mapping to Plot Space − Matplotlib maps these numerical data values to specific positions within the plot space based on the defined axis limits and scaling. Plotting Data − When we plot data using Matplotlib then we have to specify the x and y coordinates using numerical data. Matplotlib takes care of scaling and positioning these data points within the plot. Axis Limits − The limits set on the x-axis using xlim and y-axis using ylim define the range of data units displayed in the plot. Axis Ticks − The tick marks on the axes represent specific data units providing a visual reference for the data range present in the plot. Example In this example we are setting the data units of a plot. import matplotlib.pyplot as plt # Sample data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Plotting using data units plt.plot(x, y, marker=”o”) # Setting axis limits in data units plt.xlim(0, 6) # X-axis limits from 0 to 6 plt.ylim(0, 12) # Y-axis limits from 0 to 12 plt.xlabel(”X-axis (Data Units)”) plt.ylabel(”Y-axis (Data Units)”) plt.title(”Plot with Data Units”) plt.show() Output Following is the output of the above code − Understanding data units in Matplotlib is essential for accurately visualizing data and ensuring that the plotted representation corresponds correctly to the underlying numerical values. Axes Coordinates Axes coordinates range from 0.0 to 1.0 and specify the relative position within an individual subplot or axis. (0, 0) represents the bottom-left corner and (1, 1) represents the top-right corner of the subplot. Axes coordinates offer a flexible way to position annotations, text, or other elements within a subplot relative to its size and boundaries, ensuring consistent and responsive positioning across different plot sizes or dimensions. Example Here n this example we are setting the axes coordinates x and y of a plot. import matplotlib.pyplot as plt # Creating a subplot fig, ax = plt.subplots() # Plotting data ax.plot([1, 2, 3], [2, 4, 3]) # Annotating at axes coordinates ax.annotate(”Important Point”, xy=(2, 4), # Data point to annotate xytext=(0.5, 0.5), # Position in axes coordinates textcoords=”axes fraction”, # Specifying axes coordinates arrowprops=dict(facecolor=”black”, arrowstyle=”->”)) plt.show() Output Following is the output of the above code − Figure Coordinates Figure coordinates also range from 0.0 to 1.0 but specify positions relative to the entire figure canvas. (0, 0) is the
Matplotlib – Colorbars
Matplotlib – Colorbars ”; Previous Next A colorbar is a visual representation of the color scale used in a plot. It displays the color scale from the minimum to the maximum values in the data, helping us understand the color variations in the plot. In the following image you can observe a simple colorbar that is highlighted with a red color rectangle − Colorbars in Matplotlib The Matplotlib library provides a tool for working with colorbars, including their creation, placement, and customization. The matplotlib.colorbar module is responsible for creating colorbars, however a colorbar can be created using the Figure.colorbar() or its equivalent pyplot wrapper pyplot.colorbar() functions. These functions are internally uses the Colorbar class along with make_axes_gridspec (for GridSpec-positioned axes) or make_axes (for non-GridSpec-positioned axes). And a colorbar needs to be a “mappable” (i.e, matplotlib.cm.ScalarMappable) object typically an AxesImage generated via the imshow() function. If you want to create a colorbar without an attached image, you can instead use a ScalarMappable without an associated data. Example 1 Here is an simple example that creates a horizontal colorbar without an attached plotusing the ScalarMappable class. import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt # Create a figure and axis for the colorbar fig, ax = plt.subplots(figsize=(6, 1), constrained_layout=True) # Define a colormap and normalization for the colorbar cmap = mpl.cm.cool norm = mpl.colors.Normalize(vmin=5, vmax=10) # Create a ScalarMappable without associated data using the defined cmap and norm scalar_mappable = mpl.cm.ScalarMappable(norm=norm, cmap=cmap) # Add a horizontal colorbar to the figure colorbar = fig.colorbar(scalar_mappable, cax=ax, orientation=”horizontal”, label=”Some Units”) # Set the title and display the plot plt.title(”Basic Colorbar”) plt.show() Output On executing the above code we will get the following output − Example 2 Here is another example creates a simple colorbar for the plot using the pyplot.colorbar() function with default parameters. import matplotlib.pyplot as plt import numpy as np # Generate sample data data = np.random.random((10, 10)) # Create a plot with an image and a colorbar fig, ax = plt.subplots(figsize=(7,4)) im = ax.imshow(data, cmap=”viridis”) # Add a colorbar to the right of the image cbar = plt.colorbar(im, ax=ax) # Show the plot plt.show() print(”Successfully drawn the colorbar…”) Output Successfully drawn the colorbar… Automatic Colorbar Placement Automatic placement of colorbars is a straightforward approach. This ensures that each subplot has its own colorbar, providing a clear indication of the quantitative extent of the image data in each subplot. Example This example demonstrates the automatic colorbar placement for multiple subplots. import matplotlib.pyplot as plt import numpy as np # Create a 2×2 subplot grid fig, axs = plt.subplots(1, 2, figsize=(7,3)) cmaps = [”magma”, ”coolwarm”] # Add random data with different colormaps to each subplot for col in range(2): ax = axs[col] pcm = ax.pcolormesh(np.random.random((20, 20)) * (col + 1), cmap=cmaps[col]) # Add a colorbar for the each subplots fig.colorbar(pcm, ax=ax, pad=0.03) plt.show() print(”Successfully drawn the colorbar…”) Output Successfully placed the colorbar… Manual Colorbar Placement This approach allows us to explicitly determine the location and appearance of a colorbar in a plot. Which may be necessary when the automatic placement does not achieve the desired layout. By creating inset axes, either using inset_axes() or add_axes(), and then assigning it to the colorbar through the cax keyword argument, users can get the desired output. Example Here is an example that demonstrates how to determine the colorbar placement manually in a plot. import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt # Generate random data points npoints = 1000 x, y = np.random.normal(10, 2, (2, npoints)) # Create a subplot fig, ax = plt.subplots(figsize=(7,4)) # Set title plt.title(”Manual Colorbar Placement”) # Draw the plot hexbin_artist = ax.hexbin(x, y, gridsize=20, cmap=”gray_r”, edgecolor=”white”) # Manually create an inset axes for the colorbar cax = fig.add_axes([0.8, 0.15, 0.05, 0.3]) # Add a colorbar using the hexbin_artist and the manually created inset axes colorbar = fig.colorbar(hexbin_artist, cax=cax) # Display the plot plt.show() Output On executing the above code we will get the following output − Customizing Colorbars The appearance of colorbars, including ticks, tick labels, and labels, can be customized to specific requirements. Vertical colorbars typically have these elements on the y-axis, while horizontal colorbars display them on the x-axis. The ticks parameter is used to set the ticks, and the format parameter helps format the tick labels on the visible colorbar axes. Example 1 This example uses the imshow() method to display the data as an image, and places a colorbar horizontally to the image with a specified label. import matplotlib.pyplot as plt import numpy as np # Create a subplot fig, ax = plt.subplots(figsize=(7, 4)) # Generate random data data = np.random.normal(size=(250, 250)) data = np.clip(data, -1, 1) # Display the data using imshow with a specified colormap cax = ax.imshow(data, cmap=”afmhot”) ax.set_title(”Horizontal Colorbar with Customizing Tick Labels”) # Add a horizontal colorbar and set its orientation and label cbar = fig.colorbar(cax, orientation=”horizontal”, label=”A colorbar label”) # Adjust ticks on the colorbar cbar.set_ticks(ticks=[-1, 0, 1]) cbar.set_ticklabels([”Low”, ”Medium”, ”High”]) # Show the plot plt.show() Output On executing the above code we will get the following output − Example 2 This example demonstrates how to customize the position, width, color, number of ticks, font size and more properties of a colorbar. import numpy as np from matplotlib import pyplot as plt # Adjust figure size and autolayout plt.rcParams[“figure.figsize”] = [7.00, 3.50] plt.rcParams[“figure.autolayout”] = True # Generate random data data = np.random.randn(4, 4) # Plot the data with imshow im = plt.imshow(data, interpolation=”nearest”, cmap=”PuBuGn”)
Matplotlib – Setting Font Properties Globally ”; Previous Next Setting font properties globally in Matplotlib library involves configuring default font settings for the entire plot using plt.rcParams method. This is useful when we want to apply consistent font styles, sizes or families to all text elements in our visualizations without specifying them individually for each component. It”s important to note that we can tailor these settings based on our preferences and the visual style we want to achieve in our plots. We can adjust the values to match our desired font styles, sizes and families for a consistent and aesthetically pleasing appearance across our visualizations. The following are the different settings that we can make by using the plt.rcParams method. plt.rcParams[”font.family”] = font_name This sets the default font family for text elements such as ”sans-serif”. We can replace font_name with the available font families such as ”serif”, ”monospace” or specific font names. Example In this example we are trying to set the font family to ”sans-serif” by using the plt.rcParams[”font.family”]. import matplotlib.pyplot as plt # Set font properties globally plt.rcParams[”font.family”] = ”sans-serif” # Create a plot plt.plot([1, 2, 3], [4, 5, 6]) plt.xlabel(”X-axis Label”) plt.ylabel(”Y-axis Label”) plt.title(”Font Family setting”) plt.show() Output plt.rcParams[”font.size”] = font_size We can specify the default font size for text elements in numerical values as per the requirement. This ensures that all text elements use this font size unless overridden for specific components. Example In this example we are specifying the fontsize as 8 points to the plt.rcParams[”font.size”] to display font size globally all over the plot. import matplotlib.pyplot as plt # Set font properties globally plt.rcParams[”font.size”] = 8 # Create a plot plt.plot([1, 2, 3], [4, 5, 6]) plt.xlabel(”X-axis Label”) plt.ylabel(”Y-axis Label”) plt.title(”Font Size setting”) plt.show() Output plt.rcParams[”font.style”] = ”fontstyle” We can define the font style such as italic etc., as per our interest to the plt.rcParams[”font.style”]. This applies the defined appearance to text elements throughout the plot. Example In this example we are specifying the font style as italic to the plt.rcParams[”font.style”]. import matplotlib.pyplot as plt # Set font properties globally plt.rcParams[”font.style”] = ”italic” # Create a plot plt.plot([1, 2, 3], [4, 5, 6]) plt.xlabel(”X-axis Label”) plt.ylabel(”Y-axis Label”) plt.title(”Font Style setting”) plt.show() Output plt.rcParams[”font.weight”] = font_weight By using this we can set the font weight such as ”bold” etc. This makes the characters in text elements appear in the defined style as per the user requirement. Example Here in this example we are specifying the font weight as bold to the plt.rcParams[”font.weight”]. import matplotlib.pyplot as plt # Set font properties globally plt.rcParams[”font.weight”] = ”bold” # Create a plot plt.plot([1, 2, 3], [4, 5, 6]) plt.xlabel(”X-axis Label”) plt.ylabel(”Y-axis Label”) plt.title(”Font weight setting”) plt.show() Output Note − By setting these parameters globally using plt.rcParams we can ensure that these default font properties are applied to all text elements in our Matplotlib plots. When we create labels, titles or other text components they will inherit these global settings unless we specify different properties locally. Change the font properties of a Matplotlib colorbar label In this example we are changing the font properties of a matplotlib colorbar label. Example import numpy as np import matplotlib.pyplot as plt plt.rcParams[“figure.figsize”] = [7.50, 3.50] plt.rcParams[“figure.autolayout”] = True x, y = np.mgrid[-1:1:100j, -1:1:100j] z = (x + y) * np.exp(-5.0 * (x ** 2 + y ** 2)) plt.imshow(z, extent=[-1, 1, -1, 1]) cb = plt.colorbar(label=”my color bar label”) plt.show() Output Setting the size of the plotting canvas Here in this example we are setting the size of the plotting canvas in matplotlib. Example import numpy as np from matplotlib import pyplot as plt plt.rcParams[“figure.figsize”] = [7.50, 3.50] plt.rcParams[“figure.autolayout”] = True x = np.linspace(-2, 2, 100) y = np.sin(x) plt.plot(x, y) plt.show() Output Auto adjust font size in Seaborn heatmap using Matplotlib Here we are auto adjusting the font size in seaborn heatmap by using the Matplotlib library. Example import numpy as np import seaborn as sns from matplotlib import pyplot as plt import pandas as pd plt.rcParams[“figure.figsize”] = [7.00, 3.50] plt.rcParams[“figure.autolayout”] = True d = { ”y=1/x”: [1 / i for i in range(1, 10)], ”y=x”: [i for i in range(1, 10)], ”y=x^2”: [i * i for i in range(1, 10)], ”y=x^3”: [i * i * i for i in range(1, 10)] } df = pd.DataFrame(d) ax = sns.heatmap(df, vmax=1) plt.xlabel(”Mathematical Expression”, fontsize=16) plt.show() Output Set the font size of Matplotlib axis Legend In this example we are setting the font size of matplotlib axis legend Example import numpy as np from matplotlib import pyplot as plt import matplotlib plt.rcParams[“figure.figsize”] = [7.50, 3.50] plt.rcParams[“figure.autolayout”] = True x = np.linspace(1, 10, 50) y = np.sin(x) plt.plot(x, y, c=”red”, lw=7, label=”y=sin(x)”) plt.title(“Sine Curve”) matplotlib.rcParams[”legend.fontsize”] = 20 plt.legend(loc=1) plt.show() Output Modify the font size in Matplotlib-venn To work with the Matplotlib-venn, first we have to install the package by using the below code. If previously installed we can import directly. pip install matplotlib-venn Example In this example we are modifying the font size in Matplotlib-venn by using the set_fontsize() method. from matplotlib import pyplot as plt from matplotlib_venn import venn3 plt.rcParams[“figure.figsize”] = [7.50, 3.50] plt.rcParams[“figure.autolayout”] = True set1 = {”a”, ”b”, ”c”, ”d”} set2 = {”a”, ”b”, ”e”} set3 = {”a”, ”d”, ”f”} out = venn3([set1, set2, set3], (”Set1”, ”Set2”, ”Set3”)) for text in out.set_labels: text.set_fontsize(25) for text in out.subset_labels: text.set_fontsize(12) plt.show() Output Change xticks font size To change the font size of xticks in a matplotlib plot we can use the fontsize parameter. Example from matplotlib import pyplot as
Matplotlib – Arrows
Matplotlib – Arrows ”; Previous Next What are Arrows in Matplotlib? In Matplotlib library Arrows refer to the graphical elements used to indicate direction, connection between points and to highlight specific features within plots. Arrows can be added to plots using the plt.arrow() function or incorporated within annotations by using the plt.annotate() function. Arrows in Matplotlib library are versatile elements used to visually depict directionality, connections or highlights within the plots for aiding in better communication of information in visualizations. We can adjust parameters like coordinates, lengths, colors and styles to suit the specific visualization needs. The plt.arrow() function in matplotlib library creates arrows between two points on a plot. Syntax The following is the syntax and parameters of the plt.arrow() function. plt.arrow(x, y, dx, dy, kwargs) Where, x, y − These are the starting point coordinates of the arrow. dx, dy − These are lengths of the arrow in the x and y directions. kwargs − We can add additional keyword arguments to customize arrow properties such as color, width, style etc. Adding arrows to the line plot In this example we are plotting a plot by creating the arrows between the given two points on the plot by using the plt.arrow() function. To this function we passed the x, y, dx and dy points as input parameters for creating arrows in those mentioned points. In addition we passed the parameters such as length, width and color of the arrow. Example import matplotlib.pyplot as plt # Creating a line plot plt.plot([0, 1], [0, 1]) # Adding an arrow plt.arrow(0.2, 0.2, 0.4, 0.4, head_width=0.05, head_length=0.1, fc=”red”, ec=”blue”) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Arrow created by using plt.arrow() function”) # show grid of the plot plt.grid(True) plt.show() Output Adding arrow separately Here this is another example of creating the arrows. As we know arrows can also be integrated into annotations using plt.annotate() by specifying arrowprops to define arrow styles. In this example ”Arrow Annotation” is connected to point (0.5, 0.5) with an arrow style specified by arrowprops. Example import matplotlib.pyplot as plt # Creating a plot plt.plot([0, 1], [0, 1]) # Adding an arrow with annotation plt.annotate(”Arrow Annotation”, xy=(0.5, 0.5), xytext=(0.2, 0.2), arrowprops=dict(facecolor=”yellow”,ec = ”red”, arrowstyle=”->”)) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Arrow Annotation Example”) # Displaying the grid plt.grid(True) plt.show() Output Plotting distance arrows in technical drawing To plot the distance arrows in technical drawing in matplotlib we can use annotate() method with arrow properties. Example from matplotlib import pyplot as plt plt.rcParams[“figure.figsize”] = [7.50, 3.50] plt.rcParams[“figure.autolayout”] = True plt.axhline(3.5) plt.axhline(2.5) plt.annotate( ””, xy=(0.5, 3.5), xycoords=”data”, xytext=(0.5, 2.5), textcoords=”data”, arrowprops={”arrowstyle”: ””}) plt.annotate( ”$it{d=1}$”, xy=(0.501, 3.0), xycoords=”data”, xytext=(0.5, 3.5), textcoords=”offset points”) plt.show() Output Print Page Previous Next Advertisements ”;