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 – Unit Handling

Matplotlib – Unit Handling ”; Previous Next What is Unit Handling? In Matplotlib library unit handling refers to the capability of the library to manage and interpret different types of units for plotting data accurately. Matplotlib allows users to specify and work with various units for defining and displaying data on plots whether they are related to length, time, angle or other physical quantities. Key Aspects of Unit Handling in Matplotlib The below are the key aspects of unit handling in matplotlib library. Support for Various Units Matplotlib supports multiple units such as pixels, inches, centimeters, points, fractions of the figure size and more. This flexibility allows users to define plot elements like positions, sizes and spacing using the unit of their choice. Conversion and Transformation Matplotlib handles unit conversions and transformations seamlessly. It enables automatic conversion between different units when plotting or specifying attributes such as size, location or dimensions. Unit-Aware Functions Many Matplotlib functions and methods are unit-aware which means they accept arguments or parameters in different units and internally manage the conversion for plotting purposes. Functions and Techniques for Unit Handling There are few techniques and functions available for unit handling. Automatic Conversion Matplotlib automatically handles unit conversion for plotting data. When using plot() function or other plotting functions the library converts data units to display units based on the chosen coordinate system. This automatic conversion simplifies the process of plotting data in Matplotlib by handling the conversion between different units without requiring explicit conversion steps from the user. Here”s an example demonstrating auto-conversion in unit handling. Example import matplotlib.pyplot as plt # Sample data in different units time_seconds = [1, 2, 3, 4, 5] # Time in seconds distance_meters = [2, 4, 6, 8, 10] # Distance in meters plt.plot(time_seconds, distance_meters) # Matplotlib handles unit conversion plt.xlabel(”Time (s)”) plt.ylabel(”Distance (m)”) plt.title(”Auto-Conversion of Units in Matplotlib”) plt.show() Output Axis Labeling In Axis labeling we use xlabel() and ylabel() functions to label the x-axis and y-axis respectively. These functions allow us in specifying units for the axis labels. We can adjust the labels accordingly to match the units of the data being plotted. This practice helps provide context and clarity to the plotted data for anyone viewing the graph. The below is an example demonstrating how to label axes with units using Matplotlib. Example import matplotlib.pyplot as plt # Sample data time = [0, 1, 2, 3, 4] # Time in seconds distance = [0, 10, 20, 15, 30] # Distance in meters # Creating a plot plt.plot(time, distance) # Labeling axes with units plt.xlabel(”Time (s)”) plt.ylabel(”Distance (m)”) plt.title(”Distance vs. Time”) plt.show() Output Custom Units For more explicit control set_units() methods for axes ax.xaxis.set_units() and ax.yaxis.set_units() can be used to explicitly set the units for the x-axis and y-axis. This custom axis unit handling ensures that the plot displays the data using specific units such as hours for time, kilometers for distance etc and labels the axes accordingly providing context and clarity to the visualization. Here”s an example demonstrating custom axis unit handling in Matplotlib. Example import matplotlib.pyplot as plt # Sample data time_hours = [1, 2, 3, 4, 5] # Time in hours distance_km = [50, 80, 110, 140, 170] # Distance in kilometers fig, ax = plt.subplots() # Plotting the data ax.plot(time_hours, distance_km) # Customizing x-axis and y-axis units ax.xaxis.set_units(”hours”) # Set x-axis units to hours ax.yaxis.set_units(”km”) # Set y-axis units to kilometers # Labeling axes with units ax.set_xlabel(”Time”) ax.set_ylabel(”Distance”) ax.set_title(”Distance over Time”) plt.show() Output Unit Conversion Functions like convert_xunits() and convert_yunits() within plt.gca() can convert data units to display units. Here is an example demonstrating unit conversion in unit handling in Matplotlib Example import matplotlib.pyplot as plt # Specify figure size in inches plt.figure(figsize=(6, 4)) # Width: 6 inches, Height: 4 inches # Set x-axis label with different units plt.xlabel(”Distance (cm)”) # Using centimeters as units # Plotting data with specific units x = [1, 2, 3, 4] y = [10, 15, 12, 18] plt.plot(x, y) plt.title(”Plot with Unit Handling”) plt.show() Output Use Cases for Unit Handling Consistency in Measurement − Ensuring consistent units across labels, annotations and plot elements for clarity. Dimension-Agnostic Plotting − Plotting data regardless of the unit type such as length, time etc. with Matplotlib handling conversions and scaling appropriately. Customization Flexibility − Allowing users to define plot attributes using their preferred units for better control over visualizations. Print Page Previous Next Advertisements ”;

Matplotlib – LaTeX Text Formatting in Annotations

Matplotlib – LaTeX Text Formatting in Annotations ”; Previous Next What is Text formatting in LaTex? In LaTeX text formatting in annotations within figures, graphs or plots such as those created. Matplotlib library can be accomplished using a subset of LaTeX commands within the annotation text. Annotations help add explanatory labels, descriptions or notes to elements within a graph. When working with tools like Matplotlib that support LaTeX for text rendering in annotations we can use a subset of LaTeX commands to format the text within these annotations. This allows for the incorporation of styled text, mathematical expressions and special formatting within annotations. LaTeX Formatting in Annotations Includes The below are the LaTex formatting in Annotations. Let’s see them one by one. Mathematical Expressions − The mathematical expressions are given as fractions, Greek letters, superscripts and subscripts using LaTeX math mode. Text Styling − The text styling includes bold, italics, underline or different font sizes using LaTeX commands like textbf{}, textit{}, underline{} and font size commands. Special Characters − Escaping special characters like dollar signs, percentage signs or underscores using LaTeX escape sequences. Alignment − Control over alignment, though limited, using begin{flushleft}…end{flushleft}, begin{center}…end{center}, begin{flushright}…end{flushright}. In the above we have gone through different styling formats available in LaTex, now let’s see the text formatting in Annotations using LaTex. LaTeX Text Formatting in Annotations The below are the various text formatting in Annotations using LaTex. Basic Text Formatting LaTeX commands for basic text formatting can be used in annotations. The following are some. Bold − To make text bold textbf{Bold Text} Italics − To make text italic textit{Italic Text} Underline − To add an underline to text underline{Underlined Text} Font Size − LaTeX provides different font size commands such as tiny, small, large, Large, huge, Huge Annotations with Bold text using LaTex Here in this example we are using the LaText text formatting in the Annotations for making the text to look bold on a plot. Example import matplotlib.pyplot as plt # Create a simple plot x = [1, 2, 3, 4] y = [2, 5, 7, 10] plt.plot(x, y, marker=”o”, linestyle=”-”) # Add an annotation with LaTeX text formatting plt.annotate(r”textbf{Max Value}”, xy=(x[y.index(max(y))], max(y)), xytext=(2.5, 8), arrowprops=dict(facecolor=”black”, shrink=0.05), fontsize=12, color=”blue”, bbox=dict(boxstyle=”round,pad=0.3”, edgecolor=”blue”, facecolor=”lightblue”)) # Set axis labels and title plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Example Plot with LaTeX Annotation”) # Show the plot plt.show() Output On executing the above code you will get the following output − Mathematical Notation In LaTeX text formatting within mathematical notation involves using commands and syntax within math mode to stylize text elements while expressing mathematical content. It allows for the integration of text formatting features within mathematical expressions or equations. Basic Text Formatting within Mathematical Notation The basic text formatting within the mathematical notations are as follows. Bold Text This text formatting renders the enclosed text in bold within a mathematical expression. mathbf{Bold Text} Italic Text The Italic text displays the enclosed text in italics within a mathematical expression. textit{Italic Text} Sans-serif Text This renders the enclosed text in sans-serif font style within math mode. textsf{Sans-serif Text} Typewriter Text This displays the enclosed text in a typewriter or monospaced font within math mode. texttt{Typewriter Text} Important points to remember Text formatting within mathematical notation can be achieved using text{} or specific formatting commands within math mode. Some formatting commands may not work in all math environments or may need additional packages or configurations. LaTeX offers a variety of text formatting options that can be applied within mathematical expressions to enhance the presentation of text-based content. By utilizing text formatting commands within mathematical notation LaTeX allows for the integration of styled text elements within mathematical expressions by aiding in the clarity and visual appeal of mathematical content. Subscripts and Superscripts In LaTeX subscripts and superscripts are used to position text or symbols below subscripts or above superscripts the baseline of a mathematical expression. They”re commonly employed to denote indices, exponents or special annotations within mathematical notation. Subscripts Subscripts are used to create a subscript in LaTeX we can use the underscore `_`. Superscripts Superscripts to create a superscript in LaTeX we can use the caret `^`. Subscripts and Superscripts usage in Annotation of a plot In this example we are using the subscripts and superscripts usage in annotations of a plot by using the LaTex. Example import matplotlib.pyplot as plt # Generating some data points x = [1, 2, 3, 4] y = [2, 5, 7, 10] plt.plot(x, y, ”o-”, label=”Data”) # Annotating a point with a subscript and a superscript plt.annotate(r”$mathrm{Point}_{mathrm{max}}^{(4, 10)}$”, xy=(x[y.index(max(y))], max(y)), xytext=(3, 8), arrowprops=dict(facecolor=”black”, arrowstyle=”->”), fontsize=12, color=”red”) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Example Plot with Annotation”) plt.legend() plt.show() Output On executing the above code you will get the following output − Important points to remember Subscripts and superscripts can be used independently or combined within LaTeX mathematical notation. They are crucial for denoting variables, indices, exponents and other related mathematical annotations. LaTeX automatically handles the positioning and sizing of subscripts and superscripts based on the context and surrounding elements within the mathematical expression. By using subscripts and superscripts in LaTeX we can precisely express mathematical formulas and notations, improving clarity and readability within mathematical content. Combining Text and Math Combining text and math in annotations using LaTeX involves embedding both regular text and mathematical expressions within annotations in a coherent and visually effective manner. Combining Text and Math using Latex on a plot Here in this example we are combining the text and math in

Matplotlib – What is LaTeX?

Matplotlib – What is LaTeX? ”; Previous Next LaTeX is a typesetting system widely used for producing scientific and technical documents, particularly in disciplines such as mathematics, physics, computer science, engineering and academic writing. It”s highly regarded for its superior typesetting of complex mathematical equations, scientific notations, and structured text formatting. Key Aspects of LaTeX The below are the key aspects of LaTeX. Markup Language LaTeX is a markup language, meaning it uses commands and tags to format text rather than WYSIWYG which is abbreviated as What You See Is What You Get editors. Users write plain text with embedded commands that specify the structure and formatting. High-Quality Typesetting LaTeX excels in producing professional-looking documents with precise typographical and typesetting features. It handles complex structures like mathematical formulas, tables, bibliographies and cross-references exceptionally well. Package System LaTeX offers a vast array of packages that extend its functionality for specific tasks or document types, providing templates, styles and additional features. Free and Open Source LaTeX is free to use and is supported by a strong open-source community by ensuring continuous development and a rich ecosystem of packages and resources. Components of LaTeX The LaTex of matplotlib library have the following components. Let’s see each of them in detail. Document Class The document class specifies the type of document being created and defines its overall structure, layout and formatting. It acts as a template that sets the style and behavior for the entire document. Different document classes are available to suit various types of documents such as articles, reports, books, presentations and more. Preamble In LaTeX the preamble is the section of the document that precedes the main content and the begin{document} command. It is where we define the document settings, load packages, set parameters and configure global settings that apply to the entire document. The preamble acts as a setup area where we prepare LaTeX for processing the main body of the document. Document Body The document body in LaTeX is the main section where the content of our document resides. It starts after the preamble and the begin{document} command and continues until the end{document} command. This section includes the actual text, sections, subsections, equations, figures, tables and any other elements that constitute the core content of the document. Advantages of LaTeX The following are the advantages of LaTex. Quality Typesetting − Produces high-quality output, especially for scientific and technical documents. Cross-Referencing − Simplifies referencing and cross-referencing of equations, figures, tables, and sections. Version Control − Facilitates version control and collaboration through plain text-based files. Customization − Allows extensive customization of document styles, layouts and formatting. Disadvantages of LaTeX Learning Curve − Requires learning its syntax and commands which can be daunting for beginners. Limited WYSIWYG − Lack of immediate visual feedback (WYSIWYG) might be challenging for some users accustomed to graphical editors. Usage of LaTeX Academic Writing − Academic papers, theses, dissertations Scientific − Scientific reports, articles, and journals Technical Documents − Technical documentation, manuals Presentations − Presentations using tools like Beamer Basic document structure of the LaTex Syntax A basic LaTeX document structure includes − documentclass{article} begin{document} section{Introduction} This is a simple LaTeX document. subsection{Subsection} Some text in a subsection. end{document} The above code defines a basic article document with a hierarchical structure comprising a section and a subsection. LaTeX is a powerful tool for producing structured, high-quality documents especially in technical and academic fields. While it has a learning curve its ability to handle complex mathematical notations and produce professional-looking documents makes it a preferred choice for many researchers, academics and professionals. Write our own LaTeX preamble To write our own LaTeX preamble in Matplotlib we can use this example as reference. Example 1 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(-10, 10, 100) y = np.exp(x) plt.plot(x, y, color=”red”, label=”$y=e^{x}$”) plt.legend(loc=”upper right”) plt.show() Output On executing the above code you will get the following output − Latex formula in the legend of a plot using Matplotlib inside a .py file In this example we are using the Latex formula in the legend of a plot inside a .py file. Example 2 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(1, 10, 1000) y = np.sin(x) plt.plot(x, y, label=r”$sin (x)$”, c=”red”, lw=2) plt.legend() plt.show() Output On executing the above code you will get the following output − Put a little more complex equation in the label, for example, label=r”αiπ+1=0” Now, look at the legend at the top-right corner of the plot. Print Page Previous Next Advertisements ”;

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

Matplotlib – Autoscaling

Matplotlib – Autoscaling ”; Previous Next What is Autoscaling? Autoscaling in Matplotlib refers to the automatic adjustment of axis limits based on the data being plotted, ensuring that the plotted data fits within the visible area of the plot without getting clipped or extending beyond the plot boundaries. This feature aims to provide an optimal view of the data by dynamically adjusting the axis limits to accommodate the entire dataset. Key Aspects of Autoscaling in Matplotlib The below are the key aspects of Autoscaling in Matplotlib library. Automatic Adjustment In Matplotlib automatic adjustment or autoscaling refers to the process by which the library dynamically determines and sets the axis limits both x-axis and y-axis based on the data being plotted. The aim is to ensure that the entire dataset is visible within the plot without any data points being clipped or extending beyond the plot boundaries. The key aspects of automatic adjustment are as follows. Data-Based Limits − Matplotlib examines the range of the data being plotted to determine suitable minimum and maximum limits for both axes. Data Visibility − The goal is to display all data points clearly within the plot area, optimizing the view for visualization. Dynamic Updates − When the plot is created or modified, Matplotlib recalculates and adjusts the axis limits as needed to accommodate the entire data range. Preventing Clipping − Autoscaling ensures, that no data points are clipped or hidden due to the plot boundaries. Manual Override − Users can also explicitly enable autoscaling using commands like plt.axis(”auto”) or plt.axis(”tight”) to let Matplotlib dynamically adjust the axis limits. Example In this example plt.axis(”auto”) or plt.axis(”tight”) enables autoscaling by allowing Matplotlib to dynamically adjust the axis limits based on the data being plotted. The library recalculates the limits to ensure that all data points are visible within the plot area by providing an optimal view of the data. import matplotlib.pyplot as plt # Sample data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Creating a plot with autoscaling plt.plot(x, y, marker=”o”) # Automatically adjust axis limits plt.axis(”auto”) # or simply plt.axis(”tight”) for tight axis limits plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Plot with Autoscaling”) plt.show() Output Following is the output of the above code − Tight Layout In Matplotlib tight_layout() is a function that automatically adjusts the subplot parameters to ensure that the plot elements such as axis labels, titles and other items which fit within the figure area without overlapping or getting cut off. This function optimizes the layout by adjusting the spacing between subplots and other plot elements. The below are the key Aspects of tight_layout: Optimizing Layout − tight_layout() function optimizes the arrangement of subplots and plot elements within a figure to minimize overlaps and maximize space utilization. Preventing Overlapping Elements − It adjusts the padding and spacing between subplots, axes, labels and titles to prevent any overlapping or clipping of plot elements. Automatic Adjustment − This function is particularly useful when creating complex multi-subplot figures or when dealing with various plot elements. Example In this example we are automatically adjusting the layout of the subplots by ensuring that all elements such as titles, labels etc are properly spaced and fit within the figure area. import matplotlib.pyplot as plt # Creating subplots fig, axes = plt.subplots(2, 2) # Plotting in subplots for i, ax in enumerate(axes.flatten()): ax.plot([i, i+1, i+2], [i, i+1, i+2]) ax.set_title(f”Subplot {i+1}”) # Applying tight layout plt.tight_layout() plt.show() Output Following is the output of the above code − plt.axis(”auto”) This command allows us to explicitly enable autoscaling for a specific axis. Here”s how plt.axis(”auto”) is typically used, Example import matplotlib.pyplot as plt # Creating a subplot fig, ax = plt.subplots() # Plotting data ax.plot([1, 2, 3], [2, 4, 3]) plt.axis(”auto”) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Plot with Autoscaling”) plt.show() Output Following is the output of the above code − plt.axis(”tight”) In Matplotlib plt.axis(”tight”) is a command used to set the axis limits of a plot to tightly fit the range of the data being plotted. This command adjusts the axis limits to exactly encompass the minimum and maximum values of the provided data by removing any excess space between the data points and the plot edges. Example import matplotlib.pyplot as plt # Sample data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Creating a plot with tight axis limits plt.plot(x, y, marker=”o”) # Setting axis limits tightly around the data range plt.axis(”tight”) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Plot with Tight Axis Limits”) plt.show() Output Following is the output of the above code − Dynamic Updates In Matplotlib dynamic updates refer to the ability of the library to automatically adjust or update plot elements when changes are made to the data or the plot itself. This feature ensures that the visualization remains up-to-date and responsive to changes in the underlying data without requiring manual intervention. Key Points about Dynamic Updates in Matplotlib Real-Time Updates − When new data is added to an existing plot or modifications are made to the plot elements Matplotlib dynamically updates the visualization to reflect these changes. Automatic Redrawing − Matplotlib automatically redraws the plot when changes occur such as adding new data points, adjusting axis limits or modifying plot properties. Interactive Plotting − Interactive features in Matplotlib such as in Jupyter Notebooks or interactive backends allow for real-time manipulation and updates of plots in response to user interactions. Efficient Rendering − Matplotlib optimizes the rendering process to efficiently update the plot elements while maintaining visual accuracy. Example In this example the initial plot displays a sine wave.