Matplotlib – Fonts

Matplotlib – Fonts ”; Previous Next Fonts play a crucial role in customizing text elements within plots. We can control font styles, sizes, families and other properties to enhance the appearance and readability of text in our visualizations. In Matplotlib library ‘Fonts’ refer to the typefaces used for rendering text in plots and visualizations. Fonts play a significant role in customizing the appearance of text elements such as labels, titles, annotations and legends within plots. Key Aspects of Fonts in Matplotlib library Font Family − Refers to the style or category of the font. Common font families include serif, sans-serif, monospace etc. Each family has its own visual characteristics. Font Style − Determines the appearance of text such as normal, italic or oblique. Font Weight − Specifies the thickness or boldness of the font ranging from normal to various levels of boldness. Controlling Fonts in Matplotlib Setting Font Properties − We can control font properties for text elements in plots using parameters such as `fontsize`, `fontstyle`, `fontweight` and `fontfamily` in the functions such as `plt.xlabel()`, `plt.title()` etc. plt.xlabel(”X-axis Label”, fontsize=12, fontstyle=”italic”, fontweight=”bold”, fontfamily=”serif”) Global Font Configuration − Adjusting font properties globally for the entire plot using `plt.rcParams` allows us to set default font settings for consistency. plt.rcParams[”font.family”] = ”sans-serif” plt.rcParams[”font.size”] = 12 Importance of Fonts in Visualization Readability − The choice of fonts significantly impacts the readability of text elements in plots. Selecting appropriate fonts improves the clarity of visualized information. Aesthetics − Fonts contribute to the overall aesthetics of the plot by affecting its visual appeal and presentation. Emphasis and Style − Different fonts convey various tones and styles allowing users to emphasize specific elements or create a particular visual atmosphere. Setting Font Properties Globally We can configure font properties globally for the entire plot using plt.rcParams. plt.rcParams[”font.family”] = ”sans-serif” plt.rcParams[”font.size”] = 12 In the upcoming chapters let’s go through the each parameter of the fonts in detail. Common Font-related Functions in Matplotlib The following are the common font related functions in matplotlib library. plt.rcParam − plt.rcParams in Matplotlib is a dictionary-like object that allows you to globally configure various settings that affect the appearance and behavior of plots and figures. It serves as a central configuration system for Matplotlib, providing a convenient way to set default parameters for different elements in visualizations. Functions to set font properties − We can set the font properties for axis labels and titles using the plt.xlabel(), plt.ylabel() and, plt.title() functions. Setting font properties to annotations − Similarly, we can set font properties for annotations and text elements using plt.text() and, plt.annotate() functions Listing All the Available Fonts To get a list of all the fonts currently available for matplotlib we can use the font_manager.findSystemFonts() method as shown below − from matplotlib import font_manager print(“List of all fonts currently available in the matplotlib:”) print(*font_manager.findSystemFonts(fontpaths=None, fontext=”ttf”), sep=””) The above program generates the following output − List of all fonts currently available in the matplotlib: C:WINDOWSFontsPERBI___.TTFC:WINDOWSFontsARIALUNI.TTFC:WindowsFontsBRLNSR.TTFC:WindowsFontscalibri.ttfC:WINDOWSFontsBOD_PSTC.TTFC:WINDOWSFontsWINGDNG3.TTFC:WindowsFontssegoeuisl.ttfC:WindowsFontsHATTEN.TTFC:WINDOWSFontssegoepr.ttfC:WindowsFontsTCCM____.TTFC:WindowsFontsBOOKOS.TTFC:WindowsFontsBOD_B.TTFC:WINDOWSFontscorbelli.ttfC:WINDOWSFontsTEMPSITC.TTFC:WINDOWSFontsarial.ttfC:WINDOWSFontscour.ttfC:WindowsFontsOpenSans-Semibold.ttfC:WINDOWSFontspalai.ttfC:WindowsFontsebrimabd.ttfC:WindowsFontstaileb.ttfC:WindowsFontsSCHLBKI.TTFC:WindowsFontsAGENCYR.TTFC:WindowsFontstahoma.ttfC:WindowsFontsARLRDBD.TTFC:WINDOWSFontscorbeli.ttfC:WINDOWSFontsarialbd.ttfC:WINDOWSFontsLTYPEBO.TTFC:WINDOWSFontsLTYPEB.TTFC:WINDOWSFontsBELLI.TTFC:WINDOWSFontsYuGothR.ttcC:WINDOWSFontsOpenSans-Semibold.ttfC:WindowsFontstrebucbd.ttfC:WINDOWSFontsOCRAEXT.TTFC:WINDOWSFontsJUICE___.TTFC:WINDOWSFontscomic.ttfC:WindowsFontsVIVALDII.TTFC:WindowsFontsCandarali.ttfC:WINDOWSFontscomici.ttfC:WINDOWSFontsRAVIE.TTFC:WINDOWSFontsLeelUIsl.ttfC:WindowsFontsARIALNB.TTFC:WINDOWSFontsLSANSDI.TTFC:WindowsFontsseguibl.ttfC:WINDOWSFontshimalaya.ttfC:WINDOWSFontsTCBI___ …………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………… TTFC:WindowsFontsBOD_BLAR.TTFC:WINDOWSFontsebrima.ttfC:WindowsFontsLTYPEB.TTFC:WINDOWSFontsFRABKIT.TTFC:WINDOWSFontsREFSAN.TTFC:WINDOWSFontsgadugi.ttfC:WindowsFontstimes.ttfC:WINDOWSFontsMTCORSVA.TTFC:WINDOWSFontsERASDEMI.TTFC:WindowsFontshimalaya.ttfC:WINDOWSFontsgeorgiai.ttf Listing all the font families (or Name of Fonts) Here by using the below code we will get the list of the font family i.e. Name of fonts. from matplotlib import font_manager print(“List of all fonts currently available in the matplotlib:”) print(*font_manager.findSystemFonts(fontpaths=None, fontext=”ttf”), sep=””) The above program generates the following output − List of all fonts currently available in the matplotlib: cmsy10 STIXGeneral STIXSizeThreeSym DejaVu Sans Mono STIXGeneral STIXSizeOneSym …………………………………………………………….. ITC Bookman Computer Modern Times Palatino New Century Schoolbook Controlling Font Properties Font Size (`fontsize`) Set the size of text elements using the fontsize parameter in functions like plt.xlabel(), plt.ylabel(), plt.title() etc. Example In this example we are setting the size of the text by passing the fontsize parameter to the plt.xlabel(), plt.ylabel() and plt.title() functions. import matplotlib.pyplot as plt # 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”, fontsize = 10) plt.ylabel(”Y-axis cube values”, fontsize = 12) plt.title(”plot with defined font size”) plt.show() Output Font Style (`fontstyle`) We can choose the font styles such as ”normal”, ”italic”, or ”oblique” for the font that we want to use on the created plot. Example Here we are setting the font style of the fonts that we are displaying on the plot by passing fontstyle parameter as ”normal”`, ”italic”, or ”oblique” to the plt.xlabel(), plt.ylabel() and plt.title(). import matplotlib.pyplot as plt # 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”, fontsize = 10) plt.ylabel(”Y-axis cube values”, fontsize = 12) plt.title(”plot with defined font size”) plt.show() Output Font Weight (`fontweight`) Adjust the thickness of the font using weights like ”normal”, ”bold”, or numerical values such as 400, 700, etc. Example import matplotlib.pyplot as plt # 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”, fontweight=”bold”) plt.ylabel(”Y-axis cube values”, fontweight=”bold”) plt.title(”plot with defined font size”,fontweight=”bold”) plt.show() Output Changing Font Family We can modify the font family for various text elements in Matplotlib library. Some available font families are mentioned below. ”serif” − Serif fonts such as Times New Roman ”sans-serif” − Sans-serif fonts such as Arial ”monospace” − Monospaced fonts such as Courier New Change size of the fonts We can change the size of the font by using the

Matplotlib – Ticks and Tick Labels

Matplotlib – Setting Ticks and Tick Labels ”; Previous Next Ticks are the markers denoting data points on axes. Matplotlib has so far – in all our previous examples – automatically taken over the task of spacing points on the axis.Matplotlib”s default tick locators and formatters are designed to be generally sufficient in many common situations. Position and labels of ticks can be explicitly mentioned to suit specific requirements. The xticks() and yticks() function takes a list object as argument. The elements in the list denote the positions on corresponding action where ticks will be displayed. ax.set_xticks([2,4,6,8,10]) This method will mark the data points at the given positions with ticks. Similarly, labels corresponding to tick marks can be set by set_xlabels() and set_ylabels() functions respectively. ax.set_xlabels([‘two’, ‘four’,’six’, ‘eight’, ‘ten’]) This will display the text labels below the markers on the x axis. Following example demonstrates the use of ticks and labels. import matplotlib.pyplot as plt import numpy as np import math x = np.arange(0, math.pi*2, 0.05) fig = plt.figure() ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes y = np.sin(x) ax.plot(x, y) ax.set_xlabel(‘angle’) ax.set_title(”sine”) ax.set_xticks([0,2,4,6]) ax.set_xticklabels([”zero”,”two”,”four”,”six”]) ax.set_yticks([-1,0,1]) plt.show() Print Page Previous Next Advertisements ”;

Matplotlib – Spines

Matplotlib – Spines ”; Previous Next What are Spines? In Matplotlib library spines refer to the borders or edges of a plot that frame the data area. These spines encompass the boundaries of the plot defining the area where data points are displayed. By default a plot has four spines such as top, bottom, left and right. Manipulating spines in Matplotlib offers flexibility in designing the visual aspects of a plot by allowing for a more tailored and aesthetically pleasing presentation of data. Key Characteristics of Spines The following are the characteristics of spines. Borders of the Plot − Spines form the borders of the plot area enclose the region where data is visualized. Configurable Properties − Each spine top, bottom, left, and right can be customized individually by allowing adjustments to their appearance, color, thickness and visibility. Visibility Control − Spines can be made visible or hidden to modify the appearance of the plot. Uses of Spines Plot Customization − Spines allow customization of the plot”s appearance enabling adjustments to the plot”s boundaries and style. Aesthetics and Visualization − Customizing spines can enhance the aesthetics of the plot and draw attention to specific areas of interest. Types of spines Now let’s see the each and every spine available in a plot in detail. Top Spine The Top spine refers to the horizontal line at the top of the plot area that corresponds to the upper boundary of the y-axis. It”s one of the four spines such as top, bottom, left and right that form the borders around the plot. Characteristics of the Top Spine Boundary Line − The top spine represents the upper boundary of the plot area along the y-axis. Default Visibility − By default the top spine is visible in Matplotlib plots. Customization − Similar to other spines the top spine can be customized in terms of its visibility, color, linestyle and linewidth. Example In this example ax.spines[”top”].set_visible(False) hides the top spine by removing the upper boundary of the plot area along the y-axis. import matplotlib.pyplot as plt # Creating a simple plot x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] plt.plot(x, y) # Accessing and modifying the top spine ax = plt.gca() # Get the current axes ax.spines[”top”].set_visible(False) # Hide the top spine plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Plot with Hidden Top Spine”) plt.show() Output Use Cases for Modifying the Top Spine Aesthetic Control − Customizing the visibility, color or style of the top spine can improve the appearance or match specific design requirements. Adjusting Plot Boundaries − Hiding the top spine might be useful when the plot doesn”t require an upper boundary or when creating specific visual effects. Bottom Spine In Matplotlib the bottom spine refers to the horizontal line that forms the bottom border of the plot area corresponding to the x-axis. Characteristics of the Bottom Spine Association with x-axis − The bottom spine represents the border of the plot along the x-axis defining the lower boundary of the plot area. Customization − Similar to other spines the bottom spine can be customized in terms of its visibility, color, line style, thickness and position. Example of Customizing the Bottom Spine In this example by using ax.spines[”bottom”].set_color(”blue”) changes the color of the bottom spine to blue, ax.spines[”bottom”].set_linewidth(2) sets the thickness of the bottom spine to 2 and ax.spines[”bottom”].set_visible(True) ensures the bottom spine is visible if in case it was hidden. import matplotlib.pyplot as plt # Creating a simple plot x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] plt.plot(x, y) # Accessing and customizing the bottom spine ax = plt.gca() # Get the current axes ax.spines[”bottom”].set_color(”blue”) # Change the color of the bottom spine to blue ax.spines[”bottom”].set_linewidth(2) # Set the thickness of the bottom spine to 2 ax.spines[”bottom”].set_visible(True) # Make the bottom spine visible (if previously hidden) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Plot with Customized Bottom Spine”) plt.show() Output Use Cases for Bottom Spine Customization Emphasizing Axes − By customizing the bottom spine can draw attention to the x-axis and enhance the plot”s aesthetics. Highlighting Plot Boundaries − By adjusting the appearance of the bottom spine can help in delineating the plot area and improving its clarity. Left Spine In Matplotlib the left spine refers to the vertical line that forms the left border of the plot area, corresponding to the y-axis. Characteristics of the Left Spine Association with y-axis − The left spine represents the border of the plot along the y-axis defining the left boundary of the plot area. Customization − The customization of the left spine is similar to the other pines which can be customized by color, visibility, border width etc. Example of Customizing the Left Spine In this example ax.spines[”left”].set_color(”green”) changes the color of the left spine to green, ax.spines[”left”].set_linewidth(2) sets the thickness of the left spine to 2 and ax.spines[”left”].set_visible(False) ensures the left spine is invisible if in case it was visible. import matplotlib.pyplot as plt # Creating a simple plot x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] plt.plot(x, y) # Accessing and customizing the left spine ax = plt.gca() # Get the current axes ax.spines[”left”].set_color(”green”) # Change the color of the left spine to green ax.spines[”left”].set_linewidth(2) # Set the thickness of the left spine to 2 ax.spines[”left”].set_visible(False) # Make the left spine invisible (if previously visible) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Plot with Customized Left Spine”) plt.show() Output Right Spine In Matplotlib the right spine represents the vertical line forming the right border of the plot area corresponding to the y-axis on the right side. Characteristics of the Right Spine

Matplotlib – What are Fonts?

Matplotlib – What are Fonts? ”; Previous Next In Matplotlib library ‘Fonts’ refer to the typefaces used for rendering text in plots and visualizations. Fonts play a significant role in customizing the appearance of text elements such as labels, titles, annotations and legends within plots. Key Aspects of Fonts in Matplotlib library Font Family − Refers to the style or category of the font. Common font families include serif, sans-serif, monospace etc. Each family has its own visual characteristics. Font Style − Determines the appearance of text such as normal, italic or oblique. Font Weight − Specifies the thickness or boldness of the font ranging from normal to various levels of boldness. Controlling Fonts in Matplotlib Setting Font Properties − We can control font properties for text elements in plots using parameters such as `fontsize`, `fontstyle`, `fontweight` and `fontfamily` in the functions such as `plt.xlabel()`, `plt.title()` etc. plt.xlabel(”X-axis Label”, fontsize=12, fontstyle=”italic”, fontweight=”bold”, fontfamily=”serif”) Global Font Configuration − Adjusting font properties globally for the entire plot using `plt.rcParams` allows us to set default font settings for consistency. plt.rcParams[”font.family”] = ”sans-serif” plt.rcParams[”font.size”] = 12 Importance of Fonts in Visualization Readability − The choice of fonts significantly impacts the readability of text elements in plots. Selecting appropriate fonts improves the clarity of visualized information. Aesthetics − Fonts contribute to the overall aesthetics of the plot by affecting its visual appeal and presentation. Emphasis and Style − Different fonts convey various tones and styles allowing users to emphasize specific elements or create a particular visual atmosphere. Setting Font Properties Globally We can configure font properties globally for the entire plot using plt.rcParams. plt.rcParams[”font.family”] = ”sans-serif” plt.rcParams[”font.size”] = 12 In the upcoming chapters let’s go through the each parameter of the fonts in detail. Common Font-related Functions in Matplotlib The following are the common font related functions in matplotlib library. plt.rcParams plt.rcParams in Matplotlib is a dictionary-like object that allows you to globally configure various settings that affect the appearance and behavior of plots and figures. It serves as a central configuration system for Matplotlib, providing a convenient way to set default parameters for different elements in visualizations. plt.xlabel(), plt.ylabel(), plt.title() These functions are used for setting font properties for axis labels and titles. plt.text(), plt.annotate() These functions are used for specifying font properties for annotations and text elements. Get a list of all the fonts currently available To get a list of all the fonts currently available for matplotlib we can use the font_manager.findSystemFonts() method. Example from matplotlib import font_manager print(“List of all fonts currently available in the matplotlib:”) print(*font_manager.findSystemFonts(fontpaths=None, fontext=”ttf”), sep=””) Output List of all fonts currently available in the matplotlib: C:WINDOWSFontsPERBI___.TTFC:WINDOWSFontsARIALUNI.TTFC:WindowsFontsBRLNSR.TTFC:WindowsFontscalibri.ttfC:WINDOWSFontsBOD_PSTC.TTFC:WINDOWSFontsWINGDNG3.TTFC:WindowsFontssegoeuisl.ttfC:WindowsFontsHATTEN.TTFC:WINDOWSFontssegoepr.ttfC:WindowsFontsTCCM____.TTFC:WindowsFontsBOOKOS.TTFC:WindowsFontsBOD_B.TTFC:WINDOWSFontscorbelli.ttfC:WINDOWSFontsTEMPSITC.TTFC:WINDOWSFontsarial.ttfC:WINDOWSFontscour.ttfC:WindowsFontsOpenSans-Semibold.ttfC:WINDOWSFontspalai.ttfC:WindowsFontsebrimabd.ttfC:WindowsFontstaileb.ttfC:WindowsFontsSCHLBKI.TTFC:WindowsFontsAGENCYR.TTFC:WindowsFontstahoma.ttfC:WindowsFontsARLRDBD.TTFC:WINDOWSFontscorbeli.ttfC:WINDOWSFontsarialbd.ttfC:WINDOWSFontsLTYPEBO.TTFC:WINDOWSFontsLTYPEB.TTFC:WINDOWSFontsBELLI.TTFC:WINDOWSFontsYuGothR.ttcC:WINDOWSFontsOpenSans-Semibold.ttfC:WindowsFontstrebucbd.ttfC:WINDOWSFontsOCRAEXT.TTFC:WINDOWSFontsJUICE___.TTFC:WINDOWSFontscomic.ttfC:WindowsFontsVIVALDII.TTFC:WindowsFontsCandarali.ttfC:WINDOWSFontscomici.ttfC:WINDOWSFontsRAVIE.TTFC:WINDOWSFontsLeelUIsl.ttfC:WindowsFontsARIALNB.TTFC:WINDOWSFontsLSANSDI.TTFC:WindowsFontsseguibl.ttfC:WINDOWSFontshimalaya.ttfC:WINDOWSFontsTCBI___ …………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………… TTFC:WindowsFontsBOD_BLAR.TTFC:WINDOWSFontsebrima.ttfC:WindowsFontsLTYPEB.TTFC:WINDOWSFontsFRABKIT.TTFC:WINDOWSFontsREFSAN.TTFC:WINDOWSFontsgadugi.ttfC:WindowsFontstimes.ttfC:WINDOWSFontsMTCORSVA.TTFC:WINDOWSFontsERASDEMI.TTFC:WindowsFontshimalaya.ttfC:WINDOWSFontsgeorgiai.ttf Get the list of font family (or Name of Fonts) Here by using the below code we will get the list of the font family i.e. Name of fonts Example from matplotlib import font_manager print(“List of all fonts currently available in the matplotlib:”) print(*font_manager.findSystemFonts(fontpaths=None, fontext=”ttf”), sep=””) Output List of all fonts currently available in the matplotlib: cmsy10 STIXGeneral STIXSizeThreeSym DejaVu Sans Mono STIXGeneral STIXSizeOneSym …………………………………………………………….. ITC Bookman Computer Modern Times Palatino New Century Schoolbook Print Page Previous Next Advertisements ”;

Matplotlib – Axis Ranges

Matplotlib – Axis Ranges ”; Previous Next What is Axis Range? Axis range in Matplotlib refers to the span of values displayed along the x-axis and y-axis in a plot. These ranges determine the visible data within the plot area and are defined by the minimum and maximum values displayed on each axis. Customizing axis ranges in Matplotlib allows for better control over the visible data within the plot by enabling the emphasis of specific ranges or patterns to enhance the visualization. The Key Points about Axis Ranges X-axis and Y-axis Ranges − Axis ranges can be adjusted independently for the x-axis and y-axis to display specific portions of the data. Setting Ranges − We can manually set the axis ranges using functions like plt.xlim() and plt.ylim() or their equivalent methods when working with an axis object ax.set_xlim() and ax.set_ylim(). Automatic Ranges − By default the Matplotlib library automatically calculates and sets the axis ranges based on the data provided. However manual adjustment allows focusing on specific data ranges or enhancing visualization. Use Cases for Axis Ranges Zooming In or Out − Adjusting axis ranges to focus on specific parts of the data by zooming in or out within the plot. Data Emphasis − Highlighting specific ranges of the data to emphasize patterns or trends. Avoiding Clutter − We can adjust the ranges of the plot axis, to prevent the overlapping of data point to improve the visualization of certain sections of the plot. Key Concepts in Axis Range The following are the key concepts of the axis range of the plot. Let’s see each of them in detail. X-Axis Range The x-range in axis range refers to the span of values displayed along the x-axis in a plot. It determines the minimum and maximum values visible on the horizontal axis by defining the range of data shown in that dimension. In Matplotlib library we can set the x-axis range using plt.xlim() or ax.set_xlim() to specify the limits for the x-axis. This allows us to control the displayed range of data along the x-axis. Controlling the x-range in axis ranges provides flexibility in visualizing specific segments of data along the x-axis by enabling better interpretation and analysis of the plotted information. Example using plt.xlim() In this example plt.xlim(1, 5) sets the x-axis limits from 1 to 5 by defining the x-range visible in the plot to cover data points between 1 and 5 along the x-axis. import matplotlib.pyplot as plt # Sample data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Creating a plot plt.plot(x, y) # Setting x-axis limits (x-range) plt.xlim(1, 5) # Set x-axis limits from 1 to 5 plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Plot with Custom X-axis Range”) plt.show() Output Example using the ax.set_xlim() Here”s an example demonstrating the use of ax.set_xlim() to set the x-axis limits when working with an axis object ax. import matplotlib.pyplot as plt # Sample data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Creating a figure and axis fig, ax = plt.subplots() # Plotting on the axis ax.plot(x, y) # Setting x-axis limits using axis object ax.set_xlim(0, 6) # Set x-axis limits from 0 to 6 # Labeling axes and adding title ax.set_xlabel(”X-axis”) ax.set_ylabel(”Y-axis”) ax.set_title(”Plot with Custom X-axis Limits”) plt.show() Output Y-Axis Range Setting the y-axis range or limits in Matplotlib allows us to specify the range of values displayed along the vertical y-axis of a plot. We can control the minimum and maximum values shown on the y-axis to focus on specific data ranges or patterns. The setting of range or limits of the y-axis in Matplotlib can be done using the plt.ylim() function or ax.set_ylim() method when working with an axis object ax. The range of values displayed along the vertical y-axis. Setting y-axis range is beneficial for focusing on specific data ranges, highlighting trends and ensuring the visualization emphasizes the relevant parts of the data along the y-axis. Example using plt.ylim() for Y-axis Range In this example the plt.ylim(0, 12) function sets the y-axis limits from 0 to 12 by specifying the range of values displayed on the y-axis. import matplotlib.pyplot as plt # Sample data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Creating a plot plt.plot(x, y) # Setting y-axis limits plt.ylim(0, 12) # Set y-axis limits from 0 to 12 plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Plot with Custom Y-axis Range”) plt.show() Output Example using ax.set_ylim() for Y-axis Range in Subplots When working with an axis object ax we can set the y-axis limits for a specific subplot as per our requirement. In this example ax.set_ylim(0, 20) sets the y-axis limits from 0 to 20 specifically for the subplot or axis ax. import matplotlib.pyplot as plt # Sample data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Creating subplots fig, ax = plt.subplots() # Plotting on the axis ax.plot(x, y) # Setting y-axis limits using axis object ax.set_ylim(0, 20) # Set y-axis limits from 0 to 12 ax.set_xlabel(”X-axis”) ax.set_ylabel(”Y-axis”) ax.set_title(”Plot with Custom Y-axis Range”) plt.show() Output Change the range of the X-axis and Y-axis This example changes the range of X and Y axes, we can use xlim() and ylim() methods. Example import numpy as np import matplotlib.pyplot as plt plt.rcParams[“figure.figsize”] = [7.50, 3.50] plt.rcParams[“figure.autolayout”] = True x = np.linspace(-15, 15, 100) y = np.sin(x) plt.plot(x, y) plt.xlim(-10, 10) plt.ylim(-1, 1) plt.show() Output Print Page Previous Next Advertisements ”;

Matplotlib – Annotations

Matplotlib – Annotations ”; Previous Next In Matplotlib library annotations refer to the capability of adding text or markers to specific locations on a plot to provide additional information or highlight particular features. Annotations allow users to label data points and indicate trends or add descriptions to different parts of a plot. Key Aspects of Annotations in Matplotlib The following are the key aspects of annotations in matplotlib library. Text Annotations Text annotations in data visualization are used to add explanatory or descriptive text to specific points, regions, or features within a plot. Annotations help in highlighting important information, providing context, or explaining trends and patterns within the visualized data. Marker Annotations Marker annotations in data visualization typically involve placing markers or symbols on specific points of interest within a plot to highlight or provide additional information about those points. These annotations can be textual or graphical and are commonly used to draw attention to significant data points, peaks, valleys, outliers or any crucial information in a visual representation. Callouts Callouts in data visualization refer to a specific type of annotation that uses visual elements like arrows, lines, or text to draw attention to a particular area or feature within a plot. They are often used to provide additional context or explanations about specific data points or regions of interest. The plt.annotate() function in Matplotlib library is used to add an annotation to a plot. It allows us to place a text annotation with optional arrows pointing to specific data points on the plot. Syntax The following is the syntax for the plt.annotate() function. plt.annotate(text, xy, xytext=None, xycoords=”data”, textcoords=”data”, arrowprops=None, annotation_clip=None, kwargs) Where, text (str) − The text of the annotation. xy (tuple or array) − The point (x, y) to annotate. xytext (tuple or array, optional) − The position (x, y) to place the text. If None defaults to `xy`. xycoords (str, Artist, or Transform, optional) − The coordinate system that `xy` is given in. Default is ”data”. textcoords (str, Artist, or Transform, optional) − The coordinate system that `xytext` is given in. Default is ”data”. arrowprops (dict, optional) − A dictionary of arrow properties. If not None an arrow is drawn from the annotation to the text. annotation_clip (bool or None, optional) − If True the text will only be drawn when the annotation point is within the axes. If None it will take the value from rcParams[“text.clip”]. kwargs (optional) − Additional keyword arguments that are passed to Text. Adding the annotation to the plot In this example we are using the plt.annotate() function to add an annotation with the text ”Peak” at the point (3, 5) on the plot. Example import matplotlib.pyplot as plt # Plotting data x = [1, 2, 3, 4, 5] y = [2, 3, 5, 7, 11] plt.plot(x, y, marker=”o”, linestyle=”-”, color=”blue”) # Adding annotation plt.annotate(”Peak”, xy=(3, 5), xytext=(3.5, 6), arrowprops=dict(facecolor=”black”, arrowstyle=”->”), fontsize=10) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Annotated Plot”) plt.grid(True) plt.show() Output Example Here this is another example of using the ‘plt.annotations’ function for adding the annotation to the image. import matplotlib.pyplot as plt # Sample data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Plotting data plt.plot(x, y, marker=”+”, linestyle=”-”) # Adding an annotation plt.annotate(”Point of Interest”, xy=(3, 6), xytext=(3.5, 7), arrowprops=dict(facecolor=”black”, arrowstyle=”->”)) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Annotated Plot”) plt.grid(True) plt.show() Output Insert statistical annotations (stars or p-values) In this example we are inserting the statistical annotations as stars r p-values. Example import numpy as np from matplotlib import pyplot as plt plt.rcParams[“figure.figsize”] = [7.00, 3.50] plt.rcParams[“figure.autolayout”] = True x = np.linspace(-1, 1, 5) y = np.linspace(-2, 2, 5) mean_x = np.mean(x) mean_y = np.mean(y) fig, ax = plt.subplots() ax.plot(x, y, linestyle=”-.”) ax.annotate(”*”, (mean_y, mean_y), xytext=(-.50, 1), arrowprops=dict(arrowstyle=”-|>”)) fig.autofmt_xdate() plt.show() Output Annotate Matplotlib Scatter Plots Here in this example we are adding the annotations to the scatter plot that we have plotted. Example # Import necessary libraries import matplotlib.pyplot as plt import numpy as np # Create data points to be plotted x = np.random.rand(30) y = np.random.rand(30) # Define the scatter plot using Matplotlib fig, ax = plt.subplots() ax.scatter(x, y) # Add annotations to specific data points using text or arrow annotations ax.annotate(”Outlier”, xy=(0.9, 0.9), xytext=(0.7, 0.7),arrowprops=dict(facecolor=”black”, shrink=0.05)) ax.annotate(”Important point”, xy=(0.5, 0.3), xytext=(0.3, 0.1),arrowprops=dict(facecolor=”red”, shrink=0.05)) ax.annotate(”Cluster of points”, xy=(0.2, 0.5), xytext=(0.05, 0.7),arrowprops=dict(facecolor=”green”, shrink=0.05)) # Adjust the annotation formatting as needed plt.title(”Annotated Scatter Plot”) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) # Show the scatter plot with annotations plt.show() Output Annotate the points on a scatter plot with automatically placed arrows In this example we are annotating the point on a scatter plot with automatically placed arrows. Example import numpy as np from matplotlib import pyplot as plt plt.rcParams[“figure.figsize”] = [7.00, 3.50] plt.rcParams[“figure.autolayout”] = True xpoints = np.linspace(1, 10, 25) ypoints = np.random.rand(25) labels = [“%.2f” % i for i in xpoints] plt.scatter(xpoints, ypoints, c=xpoints) for label, x, y in zip(labels, xpoints, ypoints): plt.annotate( label, xy=(x, y), xytext=(-20, 20), textcoords=”offset points”, ha=”right”, va=”bottom”, bbox=dict(boxstyle=”round,pad=0.5”, fc=”yellow”, alpha=0.5), arrowprops=dict(arrowstyle=”->”, connectionstyle=”arc3,rad=0”) ) plt.show() Output Print Page Previous Next Advertisements ”;

Matplotlib – LaTeX for Mathematical Expressions

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

Matplotlib – Text

Matplotlib – Working With Text ”; Previous Next Matplotlib has extensive text support, including support for mathematical expressions, TrueType support for raster and vector outputs, newline separated text with arbitrary rotations, and unicode support. Matplotlib includes its own matplotlib.font_manager which implements a cross platform, W3C compliant font finding algorithm. The user has a great deal of control over text properties (font size, font weight, text location and color, etc.). Matplotlib implements a large number of TeX math symbols and commands. The following list of commands are used to create text in the Pyplot interface − text Add text at an arbitrary location of the Axes. annotate Add an annotation, with an optional arrow, at an arbitrary location of theAxes. xlabel Add a label to the Axes’s x-axis. ylabel Add a label to the Axes’s y-axis. title Add a title to the Axes. figtext Add text at an arbitrary location of the Figure. suptitle Add a title to the Figure. All of these functions create and return a matplotlib.text.Text() instance. Following scripts demonstrate the use of some of the above functions − import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.set_title(”axes title”) ax.set_xlabel(”xlabel”) ax.set_ylabel(”ylabel”) ax.text(3, 8, ”boxed italics text in data coords”, style=”italic”, bbox = {”facecolor”: ”red”}) ax.text(2, 6, r”an equation: $E = mc^2$”, fontsize = 15) ax.text(4, 0.05, ”colored text in axes coords”, verticalalignment = ”bottom”, color = ”green”, fontsize = 15) ax.plot([2], [1], ”o”) ax.annotate(”annotate”, xy = (2, 1), xytext = (3, 4), arrowprops = dict(facecolor = ”black”, shrink = 0.05)) ax.axis([0, 10, 0, 10]) plt.show() The above line of code will generate the following output − Print Page Previous Next Advertisements ”;

Matplotlib – Simple Plot

Matplotlib – Simple Plot ”; Previous Next In this chapter, we will learn how to create a simple plot with Matplotlib. We shall now display a simple line plot of angle in radians vs. its sine value in Matplotlib. To begin with, the Pyplot module from Matplotlib package is imported, with an alias plt as a matter of convention. import matplotlib.pyplot as plt Next we need an array of numbers to plot. Various array functions are defined in the NumPy library which is imported with the np alias. import numpy as np We now obtain the ndarray object of angles between 0 and 2π using the arange() function from the NumPy library. x = np.arange(0, math.pi*2, 0.05) The ndarray object serves as values on x axis of the graph. The corresponding sine values of angles in x to be displayed on y axis are obtained by the following statement − y = np.sin(x) The values from two arrays are plotted using the plot() function. plt.plot(x,y) You can set the plot title, and labels for x and y axes. You can set the plot title, and labels for x and y axes. plt.xlabel(“angle”) plt.ylabel(“sine”) plt.title(”sine wave”) The Plot viewer window is invoked by the show() function − plt.show() The complete program is as follows − from matplotlib import pyplot as plt import numpy as np import math #needed for definition of pi x = np.arange(0, math.pi*2, 0.05) y = np.sin(x) plt.plot(x,y) plt.xlabel(“angle”) plt.ylabel(“sine”) plt.title(”sine wave”) plt.show() When the above line of code is executed, the following graph is displayed − Now, use the Jupyter notebook with Matplotlib. Launch the Jupyter notebook from Anaconda navigator or command line as described earlier. In the input cell, enter import statements for Pyplot and NumPy − from matplotlib import pyplot as plt import numpy as np To display plot outputs inside the notebook itself (and not in the separate viewer), enter the following magic statement − %matplotlib inline Obtain x as the ndarray object containing angles in radians between 0 to 2π, and y as sine value of each angle − import math x = np.arange(0, math.pi*2, 0.05) y = np.sin(x) Set labels for x and y axes as well as the plot title − plt.xlabel(“angle”) plt.ylabel(“sine”) plt.title(”sine wave”) Finally execute the plot() function to generate the sine wave display in the notebook (no need to run the show() function) − plt.plot(x,y) After the execution of the final line of code, the following output is displayed − Print Page Previous Next Advertisements ”;

Matplotlib – Font Indexing

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