Matplotlib – Font Indexing ”; Previous Next In Matplotlib library font indexing refers to accessing and utilizing different fonts or typefaces available for rendering text elements within plots. Matplotlib library provides access to various fonts and understanding font indexing involves knowing how to use these fonts by their names or indices. This is particularly relevant when we want to use fonts that are not in the default set or if we need to use system-specific fonts. The font.family parameter in Matplotlib accepts either a string representing a known font family or an integer representing a specific font index. The numeric indices are used to reference fonts that are registered with Matplotlib library. Font Indexing in Matplotlib The following are the font indexing ways in matplotlib library. Font Families Matplotlib library offers several font families such as ”serif”, ”sans-serif”, ”monospace” and more. These font families have their unique characteristics and are used to define the general design of the typeface. Font Names Matplotlib library allows the use of specific font names to access particular fonts available on our system. Font names enable the selection of custom or installed fonts for rendering text in plots. Accessing Fonts by Name To access fonts in Matplotlib we can use both the font names and their indices if available. Font Names We can access the fonts available in matplotlib by using the font names. Here is the example of accessing the font ”Times New Roman” by using the plt.rcParams[”font.family”] method. Example import matplotlib.pyplot as plt plt.rcParams[”font.family”] = ”Times New Roman” # Creating a data x = [i for i in range(10,40)] y = [i for i in range(30,60)] # Creating a plot plt.scatter(x,y,color = ”blue”) plt.xlabel(”X-axis cube values”) plt.ylabel(”Y-axis cube values”) plt.title(”Title with Times New Roman Font”) plt.show() Output Available Fonts on the System Matplotlib library can also uses the available fonts on our system. The fonts available might vary based on the operating system such as Windows, macOS, Linux and also the installed font libraries. Indexing Fonts with findSystemFonts() Matplotlib provide the function namely matplotlib.font_manager.findSystemFonts() which returns a list of paths to available fonts on the system. Example In this example we are using the matplotlib.font_manager.findSystemFonts() function to get the required indices list of font names. import matplotlib.font_manager as fm # Get a list of available fonts font_list = fm.findSystemFonts() # Display the first five fonts path print(“The first five fonts path:”,font_list[:5]) Output The first five fonts path: [”C:\Windows\Fonts\gadugi.ttf”, ”C:\WINDOWS\Fonts\COPRGTB.TTF”, ”C:\WINDOWS\Fonts\KUNSTLER.TTF”, ”C:\Windows\Fonts\OLDENGL.TTF”, ”C:\Windows\Fonts\taileb.ttf”] Accessing Fonts by Indexing Font indexing involves knowing the names or paths of available fonts on our system. We can refer these fonts by their names, aliases or file paths to set the font family in Matplotlib plots by ensuring that the desired font is used for text elements. Example Here in this example we are accessing the fonts from the system by using the font path. import matplotlib as mpl import matplotlib.font_manager as fm plt.rcParams[”font.family”] = ”C:WindowsFontsComicz.ttf” # Creating a data x = [i for i in range(10,40)] y = [i for i in range(30,60)] # Creating a plot plt.plot(x,y,color = ”violet”) plt.xlabel(”X-axis cube values”) plt.ylabel(”Y-axis cube values”) plt.title(“The plot fonts with font indexing”) plt.show() Output Note Font indexing and availability may vary depending on the backend being used in Matplotlib library. Customizing fonts with indices might be backend-specific or require special configurations such as LaTeX rendering. Print Page Previous Next Advertisements ”;
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 – Symmetrical Logarithmic and Logit Scales ”; Previous Next Symmetrical Logarithmic Scale The Symmetrical Logarithmic scale is similar to the logarithmic scale. It often abbreviated as symlog which is a type of scale used to represent data on an axis where the values are distributed symmetrically around zero using logarithmic intervals. It provides a logarithmic-like scale for both positive and negative values while accommodating zero. To apply the Symmetrical Logarithmic scale on x-axis and y-axis, we have to use plt.xscale(‘symlog’) and plt.yscale(‘symlog’) respectively. Characteristics of Symmetrical Logarithmic Scale The symmetrical logarithmic scale has the following characteristics. Symmetrical Behavior − Represents both positive and negative values logarithmically while handling zero. Linear Near Zero − The scale is linear around zero within a specified range (linthresh) before transitioning to logarithmic behavior. Parameters for Symmetrical Logarithmic Scale linthresh − Linear threshold that determines the range around zero where the scale behaves linearly before transitioning to a logarithmic scale. When to Use Symmetrical Logarithmic Scale: Data around Zero − Suitable for datasets containing values centered around zero with a wide range of positive and negative values. Avoiding Symmetry Bias − When symmetric representation of positive and negative values is needed without bias towards either side. Importance of Symmetrical Logarithmic Scale The Symmetrical Logarithmic Scale provides a logarithmic-like scale that accommodates both positive and negative values, making it useful for visualizing datasets with a balanced distribution around zero. It also helps in highlighting smaller variations around zero while accommodating larger values without skewing the representation. Plot with Symmetrical Logarithmic Scale In this plot we are creating the symmetrical Logarithmic Scale on the y-axis by using the plt.yscale(”symlog”, linthresh=0.01). Example import matplotlib.pyplot as plt import numpy as np # Generating data for a sine wave with values around zero x = np.linspace(-10, 10, 500) y = np.sin(x) # Creating a plot with a symmetrical logarithmic scale for the y-axis plt.plot(x, y) # Set symmetrical logarithmic scale for the y-axis plt.yscale(”symlog”, linthresh=0.01) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis (symlog scale)”) plt.title(”Symmetrical Logarithmic Scale”) plt.show() Output Using a symmetrical logarithmic scale in Matplotlib allows for the visualization of datasets containing values around zero by enabling effective representation and analysis of symmetrically distributed data. Adjusting the linear threshold (linthresh) parameter is crucial to determine the range where the scale behaves linearly around zero before transitioning to a logarithmic scale. Logit Scale The Logit scale is a specialized type of scale used to represent data on an axis where the values are confined between 0 and 1. It”s specifically designed for data that exists within this range commonly encountered in probabilities or values representing probabilities. Setting the Scale The plt.xscale() and plt.yscale() functions can be used to set the scale for the x-axis and y-axis respectively. Characteristics of Logit Scale The below are the characteristics of Logit Scale. Constrains Data − Specifically used for data bounded between 0 and 1. Transformation − Utilizes the logit function to map values from the standard logistic distribution. When to Use Logit Scale Probability Data − Suitable for visualizing probabilities or values representing probabilities, especially when dealing with logistic regression or logistic models. Data within 0 to 1 Range − Specifically designed for data bounded within the 0 to 1 interval. Importance of Logit Scale The Logit Scale facilitates the visualization and analysis of data that represents probabilities or has a probabilistic interpretation. It also helps in understanding and visualizing transformations of probability-related data. Plot with the Logit Scale In this plot we are creating the Logit scale on x-axis and y-axis. Example import matplotlib.pyplot as plt import numpy as np # Generating data within the 0 to 1 range x = np.linspace(0.001, 0.999, 100) y = np.log(x / (1 – x)) # Creating a plot with a logit scale for the x-axis plt.plot(x, y) plt.xscale(”logit”) # Set logit scale for the x-axis plt.xlabel(”X-axis (logit scale)”) plt.ylabel(”Y-axis”) plt.title(”Logit Scale”) plt.show() Output Understanding and choosing the appropriate scale for a plot is important for accurately representing the underlying data and ensuring that patterns and trends are effectively communicated in visualizations. Plot yscale class linear, log, logit and symlog by name in Matplotlib library. In this plot we are plotting the yscale class linear, log, logit and symlog by name. Example import numpy as np import matplotlib.pyplot as plt plt.rcParams[“figure.figsize”] = [7.50, 3.50] plt.rcParams[“figure.autolayout”] = True y = np.random.normal(loc=0.5, scale=0.4, size=1000) y = y[(y > 0) & (y < 1)] y.sort() x = np.arange(len(y)) # linear plt.subplot(221) plt.plot(x, y) plt.yscale(”linear”) plt.title(”linear”) # log plt.subplot(222) plt.plot(x, y) plt.yscale(”log”) plt.title(”log”) # symmetric log plt.subplot(223) plt.plot(x, y – y.mean()) plt.yscale(”symlog”, linthresh=0.01) plt.title(”symlog”) # logit plt.subplot(224) plt.plot(x, y) plt.yscale(”logit”) plt.title(”logit”) plt.show() Output Print Page Previous Next Advertisements ”;
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