Matplotlib – Fill Spiral ”; Previous Next In general definition, a spiral is a geometric curve that emanates from a central point and moves farther away as it revolves around that point. Spirals exhibit a whorled pattern and come in various forms, including Archimedean spirals, and logarithmic spirals. See the below image for reference − On the other hand, a Fill Spiral refers to the visual representation of a spiral curve in which the space enclosed by the spiral is filled with a color or pattern. In this tutorial, we”ll see two different ways of creating and filling spirals using Matplotlib. the process involves defining the mathematical equations that represent the spiral and then using a function like pyplot.fill() to color the region enclosed by the spiral. Creating a Basic Fill Spiral A basic fill spiral can be defined using parametric equations in polar coordinates. The pyplot.fill() function is tthen used to fill the region enclosed by the spiral with a color. Example Here is an example that creates the basic fill spiral using the pyplot.fill() and np.concatenate() functions. import matplotlib.pyplot as plt import numpy as np # Define parameters theta = np.radians(np.linspace(0,360*5,1000)) a = 1 b = 0.2 fig, axes = plt.subplots(figsize=(7, 4)) # Create a spiral for dt in np.arange(0, 2 * np.pi, np.pi / 2.0): x = a * np.cos(theta + dt) * np.exp(b * theta) y = a * np.sin(theta + dt) * np.exp(b * theta) dt = dt + np.pi / 4.0 x2 = a * np.cos(theta + dt) * np.exp(b * theta) y2 = a * np.sin(theta + dt) * np.exp(b * theta) # Concatenate points for filling xf = np.concatenate((x, x2[::-1])) yf = np.concatenate((y, y2[::-1])) # Fill the spiral plt.fill(xf, yf) # Display the plot plt.show() Output On executing the above code we will get the following output − Creating the Logarithmic Fill Spiral A logarithmic spiral is a specific type of spiral where the radius grows exponentially with the angle. Example The example constructs the logarithmic spiral in pieces, combining segments with different parameters. import matplotlib.pyplot as plt import numpy as np # Define parameters for the logarithmic spiral a = 2 b = 0.2 # Generate theta and radius values for different pieces theta1 = np.linspace(0, np.pi * 3.0, 1000, endpoint=True) r1 = np.exp(b * theta1) * a theta2 = np.linspace(np.pi, np.pi * 4.0, 1000, endpoint=True) r2 = np.exp(b * theta1) * a theta3 = np.linspace(np.pi, 0, 1000) r3 = r1[-1] * np.ones_like(theta3) theta4 = np.linspace(np.pi, 2 * np.pi, 1000) r4 = a * np.ones_like(theta4) theta5 = np.linspace(np.pi, 2 * np.pi, 1000) r5 = r1[-1] * np.ones_like(theta5) theta6 = np.linspace(0, np.pi, 1000) r6 = a * np.ones_like(theta6) # Concatenate pieces for filling theta_final_red = np.concatenate([theta1, theta3, np.flip(theta2), theta4]) radius_red = np.concatenate([r1, r3, np.flip(r2), r4]) theta_final_blue = np.concatenate([theta1, theta5, np.flip(theta2), theta6]) radius_blue = np.concatenate([r1, r5, np.flip(r2), r6]) # Plot the filled spirals fig = plt.figure(figsize=(7,4)) ax = fig.add_subplot(111, projection=”polar”) ax.set_rmax(r1[-1]) ax.fill(theta_final_red, radius_red, “g”) ax.fill(theta_final_blue, radius_blue, “r”) # Plot the individual pieces ax.plot(theta1, r1) ax.plot(theta2, r2) # Black inner circle theta_inner = np.linspace(0, np.pi * 2.0, 1000, endpoint=True) r_inner = [a] * len(theta_inner) ax.fill(theta_inner, r_inner, c=”black”) ax.axis(False) ax.grid(False) # Display the plot plt.show() Output On executing the above code we will get the following output − Print Page Previous Next Advertisements ”;
Category: matplotlib
Matplotlib – Print Stdout
Matplotlib – Print Stdout ”; Previous Next Print − usually refers to displaying something, like text or numbers, on a screen or on paper. stdout − stands for “standard output.” It is a way for a program to send information (like text or data) out of itself. When a program “prints” something to stdout, it is essentially saying, “Here”s some information I want to show or share”. So, when you hear “print stdout” together, it means a program is sending some information to be displayed in a standard way, usually on your screen. It is a basic method for programs to communicate with users or other parts of the computer system. Print Stdout in Matplotlib The term “print stdout” is not specific to Matplotlib. It generally refers to printing output to the standard output stream in Python, which is the console or terminal where you run your Python code. In Matplotlib, if you want to print output to the console, you can use Python”s built-in print() function. For example, you can print information about your plot, data, or any messages or debugging information. Print Text on Plot Printing text on a plot in Matplotlib allows you to add labels, titles, annotations, or any other textual information to enhance the understanding of your data visualization. You can place text at specific locations on the plot to provide explanations, highlight important points, or label different elements. Example In the following example, we plot a line and add the text “Hello, Matplotlib!” to the plot using the text() function. We position the text at coordinates (2, 5) with a specified “fontsize” and “color” − import matplotlib.pyplot as plt # Creating a simple plot plt.plot([1, 2, 3], [4, 5, 6]) # Adding text annotation to the plot plt.text(2, 5, ”Hello, Matplotlib!”, fontsize=12, color=”red”) # Displaying the plot plt.show() Output Following is the output of the above code − Print Text on Polar Plot Printing text on a polar plot in Matplotlib allows you to add labels, annotations, or any other textual information to enhance the understanding of your polar visualization. Just like in Cartesian plots, you can place text at specific locations on the polar plot to provide explanations, highlight important points, or label different elements. Example In here, we create a polar plot and add the text “Polar Plot” to the plot using the text() function. We position the text at an angle of “π/2” (90 degrees) and a radius of “0.5” from the origin, with a specified fontsize, color, and horizontal alignment − import matplotlib.pyplot as plt import numpy as np # Creating a polar plot theta = np.linspace(0, 2*np.pi, 100) r = np.sin(3*theta) plt.polar(theta, r) # Adding text annotation to the polar plot plt.text(np.pi/2, 0.5, ”Polar Plot”, fontsize=12, color=”blue”, ha=”center”) # Displaying the polar plot plt.show() Output On executing the above code we will get the following output − Print Text with Rotation Printing text with rotation in Matplotlib allows you to display text at an angle, which can be useful for labeling elements with slanted or diagonal orientations, or for adding stylistic effects to your plots. Example Now, we plot a line and add rotated text to the plot using the “rotation” parameter of the text() function. We position the text “Rotated Text” at coordinates (2, 5) with a specified fontsize, color, and rotation angle of “45” degrees − import matplotlib.pyplot as plt # Creating a simple plot plt.plot([1, 2, 3], [4, 5, 6]) # Adding rotated text annotation to the plot plt.text(2, 5, ”Rotated Text”, fontsize=12, color=”purple”, rotation=45) # Displaying the plot plt.show() Output After executing the above code, we get the following output − Print Text with Box Printing text with a box in Matplotlib refers to adding textual annotations to a plot with a surrounding box, highlighting important information. These annotations can include labels, titles, or descriptions, and are enclosed within a rectangular or square-shaped box to draw attention to them. To print text with a box around it in Matplotlib, you can use the “bbox” parameter of the text() function. This parameter allows you to specify the properties of the box, such as its color, transparency, and border width. Example In the following example, we plot a line and add boxed text to the plot using the text() function. We position the text “Boxed Text” at coordinates (2, 5) with a specified fontsize, color, and a box with rounded corners, light yellow face color, and orange edge color − import matplotlib.pyplot as plt # Creating a simple plot plt.plot([1, 2, 3], [4, 5, 6]) # Adding boxed text annotation to the plot plt.text(2, 5, ”Boxed Text”, fontsize=12, color=”orange”, bbox=dict(facecolor=”lightyellow”, edgecolor=”orange”, boxstyle=”round,pad=0.5”)) # Displaying the plot plt.show() Output On executing the above code we will get the following output − Print Page Previous Next Advertisements ”;
Matplotlib – Figure Class
Matplotlib – Figure Class ”; Previous Next In Matplotlib, a Figure is a top-level container that holds all the elements of a plot or visualization. It is an overall window or canvas that contains various components like axes, labels, titles, legends, colorbars, and other elements. See the below image for reference − In the above image, the green region represents the figure and the white region is the axes area. Figure Class in Matplotlb The Figure() class in Matplotlib is a top-level artist that acts as the primary container for all plot elements. It holds everything together, including subplots, axes, titles, legends, and other artistic elements. This class is available in the matplotlib.figure module with several customization options, in addition to the Figure() class, the module also contains classes related to creating and managing figures. Creating a Figure A Figure instance is typically created using pyplot methods such as figure, subplots, and subplot_mosaic. These methods return both a Figure instance and a set of Axes, providing a convenient way to create and work with visualizations. Example Here is an example that uses the pyplot.figure() method to create a figure. import matplotlib.pyplot as plt import numpy as np # Creating the Figure instance fig = plt.figure(figsize=[7, 3], facecolor=”lightgreen”, layout=”constrained”) # Adding a title to the Figure fig.suptitle(”Figure”) # Adding a subplot (Axes) to the Figure ax = fig.add_subplot() # Setting a title for the subplot ax.set_title(”Axes”, loc=”left”, fontstyle=”oblique”, fontsize=”medium”) # Showing the plot plt.show() Output On executing the above code we will get the following output − Example This example demonstrates how to create multiple figures separately within a single script in Matplotlib. from matplotlib import pyplot as plt plt.rcParams[“figure.figsize”] = [7, 3.50] plt.rcParams[“figure.autolayout”] = True # Create Figure 1 fig1 = plt.figure(“Figure 1″) plt.plot([1, 3, 7, 3, 1], c=”red”, lw=2) plt.title(“Figure 1”) # Create Figure 2 fig2 = plt.figure(“Figure 2″) plt.plot([1, 3, 7, 3, 1], c=”green”, lw=5) plt.title(“Figure 2″) # Display both figures plt.show() Output On executing the above code you will get the following output − Creating a Figure with Grids of Subplots When creating figures, various options can be customized, including subplots, size, resolution, colors, and layout. The Figure class attributes such as figsize, dpi, facecolor, edgecolor, linewidth, and layout play crucial roles in shaping the appearance of your visualizations. Example Here is an example that uses the pyplot.subplots() method to create a 2×2 grid of subplots with multiple various customization options. import matplotlib.pyplot as plt import numpy as np # Create a 2×2 grid of subplots with various customization options fig, axs = plt.subplots(2, 2, figsize=(7, 4), facecolor=”lightgreen”, layout=”constrained”) # Super title for the entire figure fig.suptitle(”2×2 Grid of Subplots”, fontsize=”x-large”) # Display the Figure plt.show() Output On executing the above code we will get the following output − Example Here is another example that creates a more complex layout using the plt.subplot_mosaic() method. import matplotlib.pyplot as plt # Create a more complex layout using plt.subplot_mosaic() fig, axs = plt.subplot_mosaic([[”A”, ”right”], [”B”, ”right”]], facecolor=”lightgreen”, layout=”constrained”) # Add text to each subplot for ax_name, ax in axs.items(): ax.text(0.5, 0.5, ax_name, ha=”center”, va=”center”, fontsize=”large”, fontweight=”bold”, color=”blue”) # Super title for the entire figure fig.suptitle(”Complex Layout using subplot_mosaic()”, fontsize=”x-large”) # Display the Figure plt.show() Output On executing the above code we will get the following output − Saving a Figure After completing a visualization, saving Figures to disk is simple using the savefig() method. This method allows you to specify the file format (e.g., PNG, PDF) and customize options such as resolution and bounding box. Example Let’s see a simple example to save the Figure object. import matplotlib.pyplot as plt # Create a 2×2 grid of subplots with various customization options fig, axs = plt.subplots(2, 2, figsize=(7, 4), facecolor=”lightgreen”, layout=”constrained”) # Super title for the entire figure fig.suptitle(”2×2 Grid of Subplots”, fontsize=”x-large”) # Super title for the entire figure fig.suptitle(”Saving a Figure”, fontsize=”x-large”) # Display the Figure plt.show() # Save the Figure object to a file fig.savefig(”Saved Figure.png”, dpi=300) Output On executing the above program, the following figure will be saved in your working direcory − Print Page Previous Next Advertisements ”;
Matplotlib – Radian Ticks
Matplotlib – Radian Ticks ”; Previous Next A radian is a unit of angular measure used to express angles in mathematics and physics. Ticks, in the field of data visualization, refer to the small lines or marks indicating the scale of the axes. Radian Ticks in Matplotlib In the context of Matplotlib, radian ticks typically denote the ticks or markers on an axis that represent values in radians. When dealing with circular or angular data, it is common to use radian ticks on the axis to indicate specific angles. Setting radian ticks involves placing tick marks at specific intervals corresponding to certain radian values on the axis. Here is a reference image illustrating Radian ticks on a plot − In the image, you can observe that radian ticks represent the angles of the sine wave along the x-axis. Radian Ticks for the x axis Setting Radian Ticks for the x-axis involves using two key methods which are axes.set_xticks() and axes.set_xticklabels(). These methods are allowing you to specify the positions and labels of ticks on the x-axis, respectively. In addition to these methods, the FormatStrFormatter and MultipleLocator classes from the matplotlib.ticker module can be used to enhance the customization of tick positions and labels. Example 1 The following example demonstrates how to create a plot with custom radian ticks. import matplotlib.pyplot as plt import numpy as np # Create plot fig, ax = plt.subplots(figsize=(7, 4)) # Sample data theta = np.linspace(0, 2 * np.pi, 100) y = np.sin(theta) # Plotting the data plt.plot(theta, y) plt.title(”Sine Wave”) plt.xlabel(”Angle (radians)”) plt.ylabel(”Y-axis”) # Custom radian ticks and tick labels custom_ticks = [0, np.pi/2, np.pi, (3*np.pi)/2, 2*np.pi] custom_tick_labels = [”$0$”, ”$pi/2$”, ”$pi$”, ”$3pi/2$”, ”$2pi$”] ax.set_xticks(custom_ticks) ax.set_xticklabels(custom_tick_labels) plt.grid(axis=”x”) # Display the plot plt.show() Output On executing the above code we will get the following output − Example 2 This example uses the FormatStrFormatter and MultipleLocator classes from the matplotlib.ticker module to control the format and positions of ticks. import matplotlib.pyplot as plt import matplotlib.ticker as tck import numpy as np # Create Plot f,ax=plt.subplots(figsize=(7,4)) # Sample Data x=np.linspace(0, 2 * np.pi, 100) y=np.sin(x) # Plot the sine wave ax.plot(x/np.pi,y) # Customizing X-axis Ticks ax.xaxis.set_major_formatter(tck.FormatStrFormatter(”%g $pi$”)) ax.xaxis.set_major_locator(tck.MultipleLocator(base=1.0)) # Set the titles plt.title(”Sine Wave”) plt.xlabel(”Angle (radians)”) plt.ylabel(”Y-axis”) plt.grid() plt.show() Output On executing the above code we will get the following output − Radian Ticks for the y axis Similar to the x-axis, setting radian ticks for the y-axis can be done by using the ax.set_yticks() and ax.set_yticklabels() methods. These methods allow you to define the positions and labels of ticks on the y-axis. Additionally, the FormatStrFormatter and MultipleLocator classes from the matplotlib.ticker module can also used. Example This example demonstrates how to set customized radian ticks for the y-axis. using the FormatStrFormatter and MultipleLocator classes from the matplotlib.ticker module. import matplotlib.pyplot as plt import matplotlib.ticker as tck import numpy as np # Create Plot f,ax=plt.subplots(figsize=(7,4)) # Sample Data x=np.arange(-10.0,10.0,0.1) y=np.arctan(x) # Plot the data ax.plot(x/np.pi,y) # Customizing y-axis Ticks ax.yaxis.set_major_formatter(tck.FormatStrFormatter(”%g $pi$”)) ax.yaxis.set_major_locator(tck.MultipleLocator(base=0.5)) plt.grid() plt.show() Output On executing the above code we will get the following output − Custom Package for Radian Ticks A custom package named “basic_units.py” can denote the tick marks using the radians. This package is not part of the standard or widely recognized packages and needs to be downloaded separately(available in the examples folder of Matplotlib). Example This example demonstrates how to create a plot with radians using the basic_units mockup example package. import matplotlib.pyplot as plt from basic_units import radians import numpy as np # Create Plot f,ax=plt.subplots(figsize=(7,4)) x = np.arange(-10.0,10.0,0.1) y = list(map(lambda y: y*radians,np.arctan(x))) x = list(map(lambda x: x*radians,x)) ax.plot(x,y,”b.”) plt.xlabel(”radians”) plt.ylabel(”radians”) plt.show() Output On executing the above code we will get the following output − Print Page Previous Next Advertisements ”;
Matplotlib – LaTeX
Matplotlib – Latex ”; Previous Next What is LaTeX? 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 behaviour 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. Writing 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 This will generate the following output − Example 2 In this example we are using the Latex formula in the legend of a plot inside a .py file. 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 This will generate 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. Example 3 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(r”αiπ+1=0”) plt.show() Output This will generate the following output − 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
Matplotlib – Axis Ticks
Matplotlib – Axis Ticks ”; Previous Next What are Axis Ticks? Axis ticks in Matplotlib refer to the markers along the axes that denote specific data values. They aid in understanding the scale of the plot and provide reference points for data visualization. Let”s delve into the details of axis ticks − Key Concepts in Axis ticks The below are the key concepts available in axis ticks. Major Ticks − These are the prominent ticks along the axis that represent significant data values. Minor Ticks − These are the smaller ticks between major ticks which provides more granularity in the scale but usually less prominent. Customizing Axis Ticks We can customize the axis ticks on the plot as per the requirement and need. There are few steps to be followed to perform customization. Setting Ticks We can set the axis ticks in two ways, one is by manual setting and the other is by automatic adjustment. Manual Setting We can set specific tick locations and labels for the axis using plt.xticks() or plt.yticks() functions. Example import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10, 100) y = np.sin(x) plt.plot(x, y) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Plot with Custom Axis Ticks”) # Customize x-axis ticks plt.xticks([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [”A”, ”B”, ”C”, ”D”, ”E”, ”F”, ”G”, ”H”, ”I”, ”J”, ”K”]) # Customize y-axis ticks and labels plt.yticks([-1, 0, 1], [”Min”, ”Zero”, ”Max”]) plt.show() Output Automatic Adjustment In Matplotlib the automatic adjustment of axis ticks involves letting the library determine the positions and labels of ticks based on the data range. This process is handled by default when we create a plot but we can fine-tune the automatic adjustment using various formatting options or by adjusting the locator and formatter settings. Here are some aspects related to automatic adjustment of axis ticks. Default Automatic Adjustment In this example Matplotlib automatically adjusts the positions and labels of ticks based on the data range. Example import matplotlib.pyplot as plt # Example data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Creating a plot (automatic adjustment of ticks) plt.plot(x, y) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Automatic Adjustment of Axis Ticks”) plt.show() Output Customizing Automatic Adjustment We can customize the ticks automatically by using few functions available in pyplot. These adjustments can be made to suit the nature of our data and enhance the readability of the plot. Understanding and leveraging automatic adjustment of axis ticks is crucial for creating clear and informative visualizations in Matplotlib. Adjusting the Number of Ticks We can use plt.locator_params(axis=”x”, nbins=5) to control the number of ticks on the x-axis. Adjust the parameter nbins set to the desired number. Scientific Notation To display tick labels in scientific notation we can use the plt.ticklabel_format(style=”sci”, axis=”both”, scilimits=(min, max)). Date Ticks (For Time Series Data) If we are dealing with date/time data then Matplotlib can automatically format date ticks. Example In this example we are applying the customizing automatic adjustment to the axis ticks of the plot. import matplotlib.dates as mdates from datetime import datetime # Example date data dates = [datetime(2022, 1, 1), datetime(2022, 2, 1), datetime(2022, 3, 1)] # Creating a plot with automatic adjustment of date ticks plt.plot(dates, [2, 4, 6]) # Formatting x-axis as date plt.gca().xaxis.set_major_locator(mdates.MonthLocator()) plt.gca().xaxis.set_major_formatter(mdates.DateFormatter(”%Y-%m-%d”)) plt.xlabel(”Date”) plt.ylabel(”Y-axis”) plt.title(”Automatic Adjustment of Date Ticks”) plt.show() Output Tick Formatting We can customize the appearance of tick labels based on font size, color and rotation using fontsize, color and rotation parameters. Example import matplotlib.pyplot as plt # Example data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Creating a plot (automatic adjustment of ticks) plt.plot(x, y) plt.xticks(fontsize=10, color=”red”, rotation=45) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Automatic Adjustment of Axis Ticks”) plt.show() Output Tick Frequency and Appearance Setting Tick Frequency We can adjust the frequency of ticks using plt.locator_params(axis=”x”, nbins=5) to control the number of ticks displayed. Example import matplotlib.pyplot as plt # Example data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Creating a plot (automatic adjustment of ticks) plt.plot(x, y) plt.locator_params(axis=”x”, nbins=10) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Automatic Adjustment of Axis Ticks”) plt.show() Output Minor Ticks We can enable the minor ticks using plt.minorticks_on(). We can customize their appearance with plt.minorticks_on(), plt.minorticks_off() or by specifying their positions. Example import matplotlib.pyplot as plt # Example data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Creating a plot (automatic adjustment of ticks) plt.plot(x, y) plt.minorticks_on() plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Automatic Adjustment of Axis Ticks”) plt.show() Output Use Cases Precision Control − Adjust ticks to provide more precise information about data values. Enhanced Readability − Customize tick labels and appearance for better readability. Fine-tuning − Manually set ticks to emphasize specific data points or intervals. Understanding and customizing axis ticks is crucial for effectively communicating information in plots by allowing us to tailor the presentation of data according to our visualization needs. Adding extra axis ticks In this example to add extra ticks we use xticks() function and increase the range of ticks to 1 to 20 from 1 to 10. Example import numpy as np from matplotlib import pyplot as plt plt.rcParams[“figure.figsize”] = [7.50, 3.50] plt.rcParams[“figure.autolayout”] = True x = np.linspace(1, 10, 100) y = np.sin(x) plt.plot(x, y) plt.xticks(range(1, 20)) plt.show() Output Customize X-axis ticks In this example to add extra ticks we use xticks() function and increase the range of ticks to 1 to 20 from 1 to 10. Example import numpy as
Matplotlib – Tick Formatters
Matplotlib – Tick Formatters ”; Previous Next Understanding Ticks and Tick Labels In general graphs and plotting, ticks are the small lines that show the scale of x and y-axes, providing a clear representation of the value associated with each tick. Tick labels are the textual or numeric annotations associated with each tick on an axis, providing a clear representation of the value associated with each tick. The following image represents the ticks and tick labels on a graph − In this context Tick formatters, controls the appearance of the tick labels, specifying how the tick notations are displayed. This customization can include formatting options like specifying decimal places, adding units, using scientific notation, or applying date and time formats. Tick Formatters in Matplotlib Matplotlib allows users to customize tick properties, including locations and labels, through the matplotlib.ticker module. This module contains classes for configuring both tick locating and formatting. It provides a range of generic tick locators and formatters, as well as domain-specific custom ones. To set the tick format, Matplotlib allows ypu to use either − a format string, a function, or an instance of a Formatter subclass. Applying Tick Formatters Matplotlib provides a straightforward way to configure tick formatters using the set_major_formatter and set_minor_formatter functions. These functions enable you to set the major and minor tick label formats for a specific axis. The syntax is as follows − Syntax ax.xaxis.set_major_formatter(xmajor_formatter) ax.xaxis.set_minor_formatter(xminor_formatter) ax.yaxis.set_major_formatter(ymajor_formatter) ax.yaxis.set_minor_formatter(yminor_formatter) String Formatting String Formatting is a technique, which implicitly creates the StrMethodFormatter method, allowing you to use new-style format strings (str.format). Example In this example, the x-axis tick labels will be formatted using a string. import matplotlib.pyplot as plt from matplotlib import ticker # Create a sample plot fig, ax = plt.subplots(figsize=(7,4)) ax.plot([1, 2, 3, 4], [10, 20, 15, 20]) # Set up the major formatter for the x-axis ax.xaxis.set_major_formatter(”{x} km”) ax.set_title(”String Formatting”) plt.show() Output On executing the above code we will get the following output − Function Based Formatting This approach provides a flexible way to customize tick labels using a user-defined function. The function should accept two inputs: x (the tick value) and pos (the position of the tick on the axis). Then it returns a string representing the desired tick label corresponding to the given inputs. Example This example demonstrates using a function to format x-axis tick labels. from matplotlib.ticker import FuncFormatter from matplotlib import pyplot as plt def format_tick_labels(x, pos): return ”{0:.2f}%”.format(x) # sample data values = range(20) # Create a plot f, ax = plt.subplots(figsize=(7,4)) ax.plot(values) # Set up the major formatter for the x-axis using a function ax.xaxis.set_major_formatter(FuncFormatter(format_tick_labels)) ax.set_title(”Function Based Formatting”) plt.show() Output On executing the above code we will get the following output − Formatter Object Formatting Formatter object Formatting allows for advanced customization of tick labels using specific formatter subclass. Some common Formatter subclasses include − NullFormatter − This object ensures that no labels are displayed on the ticks. StrMethodFormatter − This object utilizes the string str.format method for formatting tick labels. FormatStrFormatter − This object employs %-style formatting for tick labels. FuncFormatter − It define labels through a custum function. FixedFormatter − It allows users to set label strings explicitly. ScalarFormatter − It is the default formatter for scalars. PercentFormatter − It format labels as percentages. Example 1 The following example demonstrates how different Formatter Objects can be applied to the x-axis to achieve different formatting effects on tick labels. from matplotlib import ticker from matplotlib import pyplot as plt # Create a plot fig, axs = plt.subplots(5, 1, figsize=(7, 5)) fig.suptitle(”Formatter Object Formatting”, fontsize=16) # Set up the formatter axs[0].xaxis.set_major_formatter(ticker.NullFormatter()) axs[0].set_title(”NullFormatter()”) # Add other formatters axs[1].xaxis.set_major_formatter(ticker.StrMethodFormatter(“{x:.3f}”)) axs[1].set_title(”StrMethodFormatter(“{x:.3f}”)”) axs[2].xaxis.set_major_formatter(ticker.FormatStrFormatter(“#%d”)) axs[2].set_title(”FormatStrFormatter(“#%d”)”) axs[3].xaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True)) axs[3].set_title(”ScalarFormatter(useMathText=True)”) axs[4].xaxis.set_major_formatter(ticker.PercentFormatter(xmax=5)) axs[4].set_title(”PercentFormatter(xmax=5)”) plt.tight_layout() plt.show() Output On executing the above code we will get the following output – Example 2 This example demonstrates how to format tick labels on both the x-axis and y-axis using a string formatting method (StrMethodFormatter) to display the numbers with comma separators. import matplotlib.pyplot as plt from matplotlib.ticker import StrMethodFormatter # Data x = [10110, 20110, 40110, 6700] y = [20110, 10110, 30110, 9700] # Create plot fig, ax = plt.subplots(figsize=(7, 4)) ax.plot(x, y) # Format tick labels for both x-axis and y-axis to include comma separators ax.yaxis.set_major_formatter(StrMethodFormatter(”{x:,}”)) ax.xaxis.set_major_formatter(StrMethodFormatter(”{x:,}”)) # Show plot plt.show() Output On executing the above code you will get the following output − Print Page Previous Next Advertisements ”;
Matplotlib – Animations
Matplotlib – Animations ”; Previous Next Animation is a visual technique that involves the creation of moving images through a sequence of individual frames. Each frame represents a specific moment in time, and when played consecutively at a high speed, they create the illusion of movement. For instance, a common example of an animated object is a GIF. Here is an example − The popular file formats of animations are GIFs, APNG (Animated Portable Network Graphics), mkv, mp4, and more. Animations in Matplotlib Matplotlib provides a dedicated module for creating animations. In this context, an animation is a series of frames, and each frame is associated with a plot on a Figure. To integrate the animation capabilities into our working environment we can import the dedicated module by using the following command − import matplotlib.animation as animation Creating Animations Creating animations in Matplotlib can be done through two different approaches. The matplotlib.animation module provides two primary classes for this purpose − FuncAnimation ArtistAnimation The FuncAnimation class The approach of Using the FuncAnimation class is an efficient way to create animations by modifying the data of a plot for each frame. It allows us to create an animation by passing a user-defined function that iteratively modifies the data of a plot. This class involves generating data for the initial frame and subsequently modifying this data for each subsequent frame. Example This example demonstrates the use of FuncAnimation class to animate a sine wave plot, illustrating the motion of the object. And it is also updates the X-axis values using Matplotlib animation. import matplotlib.pyplot as plt import numpy as np import matplotlib.animation as animation # Creating a figure and axis fig, ax = plt.subplots(figsize=(7, 4)) # Generating x values x = np.arange(0, 2*np.pi, 0.01) # Plotting the initial sine curve line, = ax.plot(x, np.sin(x)) ax.legend([r”$sin(x)$”]) # Function to update the plot for each frame of the animation def update(frame): line.set_ydata(np.sin(x + frame / 50)) ax.set_xlim(left=0, right=frame) return line # Creating a FuncAnimation object ani = animation.FuncAnimation(fig=fig, func=update, frames=40, interval=30) # Displaying the output plt.show() Output The above example produces the following output − Example Here is another example that creates an animated 3D surface plot using FuncAnimation class. import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation # Generate data N = 50 fps = 250 frn = 75 x = np.linspace(-2, 2, N + 1) x, y = np.meshgrid(x, x) zarray = np.zeros((N + 1, N + 1, frn)) f = lambda x, y, sig: 1 / np.sqrt(sig) * np.exp(-(x ** 2 + y ** 2) / sig ** 2) # Create data array for i in range(frn): zarray[:, :, i] = f(x, y, 1.5 + np.sin(i * 2 * np.pi / frn)) # Update plot function def change_plot(frame_number, zarray, plot): plot[0].remove() plot[0] = ax.plot_surface(x, y, zarray[:, :, frame_number], cmap=”afmhot_r”) # Create figure and subplot fig = plt.figure(figsize=(7, 4)) ax = fig.add_subplot(111, projection=”3d”) # Initial plot plot = [ax.plot_surface(x, y, zarray[:, :, 0], color=”0.75”, rstride=1, cstride=1)] # Set axis limits ax.set_zlim(0, 1.1) # Animation ani = animation.FuncAnimation(fig, change_plot, frn, fargs=(zarray, plot), interval=1000 / fps) # Turn off axis and grid ax.axis(”off”) ax.grid(False) # Show plot plt.show() Output The above example produces the following output − ArtistAnimation ArtistAnimation is a flexible approach suitable for scenarios where different artists need to be animated in a sequence. This approach involves generating a list (iterable) of artists to draw them into each frame of the animation. Example This example demonstrates the using of ArtistAnimation class to create the animation. import matplotlib.pyplot as plt import numpy as np import matplotlib.animation as animation # Create a figure and axis fig, ax = plt.subplots(figsize=(7,4)) # Define the function def f(x, y): return np.sin(x) + np.cos(y) # Generate x and y values for the function x = np.linspace(0, 2 * np.pi, 180) y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1) # ims is a list of lists, each row is a list of artists to draw in the current frame ims = [] # Generate frames for the animation for i in range(60): x += np.pi / 10 y += np.pi / 30 im = ax.imshow(f(x, y), animated=True) if i == 0: ax.imshow(f(x, y)) # show an initial one first ims.append([im]) # Create an ArtistAnimation with the specified interval, blit, and repeat_delay ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True, repeat_delay=1000) # Display the animation plt.show() Output The above code generates the following results − Saving animations Saving animation objects to disk is possible using different multimedia writers, such as Pillow, ffmpeg, and imagemagick. However, it”s important to note that not all video formats are supported by every writer. There are four primary types of writers: PillowWriter HTMLWriter Pipe-based writers File-based writers PillowWriter It uses the Pillow library to save animations in various formats, such as GIF, APNG, and WebP. Example An example demonstrates animating a scatterplot and saving that as a GIF using the PillowWriter. import matplotlib.pyplot as plt import matplotlib.animation as animation import numpy as np # Generate data steps = 50 nodes = 100 positions = [] solutions = [] for i in range(steps): positions.append(np.random.rand(2, nodes)) solutions.append(np.random.random(nodes)) # Create a figure and axes fig, ax = plt.subplots(figsize=(7, 4)) marker_size = 50 # Function to update the plot for each frame of the animation def animate(i): fig.clear() ax = fig.add_subplot(111, aspect=”equal”, autoscale_on=False, xlim=(0, 1), ylim=(0, 1)) ax.set_xlim(0, 1) ax.set_ylim(0, 1) s = ax.scatter(positions[i][0], positions[i][1], s=marker_size, c=solutions[i], cmap=”RdBu_r”, marker=”o”, edgecolor=”black”) plt.grid(None) # Creating a FuncAnimation object ani = animation.FuncAnimation(fig, animate,
Matplotlib – Multiprocessing
Matplotlib – Multiprocessing ”; Previous Next Multiprocessing is a technique used to execute multiple processes concurrently, taking advantage of multi-core processors. In Python, the multiprocessing module provides a convenient way to create and manage parallel processes. This is useful for tasks that can be parallelized, such as generating plots, running simulations, or performing computations on large datasets. Multiprocessing in Matplotlib Matplotlib is traditionally used in a single-threaded manner, combining it with the multiprocessing library allows for the creation of plots in parallel. This can be useful when dealing with a large number of plots or computationally intensive tasks. Creating Multiple Matplotlib Plots Creating multiple plots sequentially can lead to a slower execution, especially when dealing with a large number of plots. In such cases, using the multiprocessing technique can significantly improve performance by allowing the creation of multiple plots concurrently. Example Let”s see a basic example that demonstrates how to create multiple Matplotlib plots in parallel using multiprocessing. import matplotlib.pyplot as plt import numpy as np import multiprocessing def plot(datax, datay, name): x = datax y = datay**2 plt.scatter(x, y, label=name) plt.legend() plt.show() def multiP(): for i in range(4): p = multiprocessing.Process(target=plot, args=(i, i, i)) p.start() if __name__ == “__main__”: input(”Press Enter to start parallel plotting…”) multiP() Output On executing the above program, 4 matplotlib plots are created in parallel see the video below for reference − Saving Multiple Matplotlib Figures Saving multiple Matplotlib figures concurrently is another scenario where multiprocessing can be advantageous. Example 1 Here is an example that uses multiprocessing to save multiple Matplotlib figures concurrently. import matplotlib.pyplot as plt import numpy.random as random from multiprocessing import Pool def do_plot(number): fig = plt.figure(number) a = random.sample(1000) b = random.sample(1000) # generate random data plt.scatter(a, b) plt.savefig(“%03d.jpg” % (number,)) plt.close() print(f”Image {number} saved successfully…”) if __name__ == ”__main__”: pool = Pool() pool.map(do_plot, range(1, 5)) Output On executing the above code we will get the following output − Image 1 saved successfully… Image 2 saved successfully… Image 3 saved successfully… Image 4 saved successfully… If you navigate to the directory where the plots were saved, you will be able to observe the ved 001.jpg, 002.jpg, 003.jpg, and 004.jpg images as shown below − Example 2 Here is another example that demonstrates how to use multiprocessing to generate data in one process and plot it in another using Matplotlib. import multiprocessing as mp import time import matplotlib.pyplot as plt import numpy as np # Fixing random state for reproducibility np.random.seed(19680801) class ProcessPlotter: def __init__(self): self.x = [] self.y = [] def terminate(self): plt.close(”all”) def call_back(self): while self.pipe.poll(): command = self.pipe.recv() if command is None: self.terminate() return False else: self.x.append(command[0]) self.y.append(command[1]) self.ax.plot(self.x, self.y, ”ro”) self.fig.canvas.draw() return True def __call__(self, pipe): print(”Starting plotter…”) self.pipe = pipe self.fig, self.ax = plt.subplots() timer = self.fig.canvas.new_timer(interval=1000) timer.add_callback(self.call_back) timer.start() print(”…done”) plt.show() class NBPlot: def __init__(self): self.plot_pipe, plotter_pipe = mp.Pipe() self.plotter = ProcessPlotter() self.plot_process = mp.Process( target=self.plotter, args=(plotter_pipe,), daemon=True) self.plot_process.start() def plot(self, finished=False): send = self.plot_pipe.send if finished: send(None) else: data = np.random.random(2) send(data) # Main function for the integrated code def main_with_multiprocessing(): pl = NBPlot() for _ in range(10): pl.plot() time.sleep(0.5) pl.plot(finished=True) if __name__ == ”__main__”: if plt.get_backend() == “MacOSX”: mp.set_start_method(“forkserver”) input(”Press Enter to start integrated example…”) main_with_multiprocessing() Output On executing the above program, will generate the matplotlib plots with random data see the video below for reference − Print Page Previous Next Advertisements ”;
Matplotlib – Tick Locators
Matplotlib – Tick Locators ”; Previous Next In general graphs and plottings, ticks play a crucial role in representing the scale of x and y-axes through small lines, offering a clear indication of the associated values. Tick locators, on the other hand, define the positions of these ticks along the axis, offering a visual representation of the scale. The below image represents the major and minor ticks on a graph − Tick Locators in Matplotlib Matplotlib provides a mechanism for controlling the positioning of ticks on axes through its tick locators. The matplotlib.ticker module contains classes for configuring tick locating and formatting. These classes include generic tick locators, Formatters, and domain-specific custom ones. While locators are unaware of major or minor ticks, they are used by the Axis class to support major and minor tick locating and formatting. Different Tick Locators The matplotlib provides different tick locator within its ticker module, allowing users to customize the tick positions on axes. Some of the Tick Locators include − AutoLocator MaxNLocator LinearLocator LogLocator MultipleLocator FixedLocator IndexLocator NullLocator SymmetricalLogLocator AsinhLocator LogitLocator AutoMinorLocator Defining Custom Locators Basic Setup Before diving into specific tick locators, let”s establish a common setup function to draw the plot with ticks. import matplotlib.pyplot as plt import numpy as np import matplotlib.ticker as ticker def draw_ticks(ax, title): # it shows the bottom spine only ax.yaxis.set_major_locator(ticker.NullLocator()) ax.spines[[”left”, ”right”, ”top”]].set_visible(False) ax.xaxis.set_ticks_position(”bottom”) ax.tick_params(which=”major”, width=1.00, length=5) ax.tick_params(which=”minor”, width=0.75, length=2.5) ax.set_xlim(0, 5) ax.set_ylim(0, 1) ax.text(0.0, 0.2, title, transform=ax.transAxes, fontsize=14, fontname=”Monospace”, color=”tab:blue”) Now, let”s explore the working of each tick locator. Auto Locator The AutoLocator and AutoMinorLocator are used for automatically determining the positions of major and minor ticks on an axis, respectively. Example This example demonstrates how to use the AutoLocator and AutoMinorLocator to automatically handle the positioning of major and minor ticks on an axis. # Auto Locator fig, ax = plt.subplots(1,1,figsize=(7,1.5), facecolor=”#eaffff”) plt.subplots_adjust(bottom=0.3, top=0.6, wspace=0.2, hspace=0.4) draw_ticks(ax, title=”AutoLocator() and AutoMinorLocator()”) ax.xaxis.set_major_locator(ticker.AutoLocator()) ax.xaxis.set_minor_locator(ticker.AutoMinorLocator()) ax.set_title(”Auto Locator and Auto Minor Locator”) plt.show() Output Null Locator The NullLocator places no ticks on the axis. Example Let’s see the following example for working of the NullLocator. # Null Locator fig, ax = plt.subplots(1,1,figsize=(7,1.5), facecolor=”#eaffff”) plt.subplots_adjust(bottom=0.3, top=0.6, wspace=0.2, hspace=0.4) draw_ticks(ax, title=”NullLocator()”) ax.xaxis.set_major_locator(ticker.NullLocator()) ax.xaxis.set_minor_locator(ticker.NullLocator()) ax.set_title(”Null Locator (No ticks)”) plt.show() Output Multiple Locator The MultipleLocator() class allows ticks to be positioned at multiples of a specified base, supporting both integer and float values. Example The following example demonstrates how to use the MultipleLocator() class. # Multiple Locator fig, ax = plt.subplots(1,1,figsize=(7,1.5), facecolor=”#eaffff”) plt.subplots_adjust(bottom=0.3, top=0.6, wspace=0.2, hspace=0.4) draw_ticks(ax, title=”MultipleLocator(0.5)”) ax.xaxis.set_major_locator(ticker.MultipleLocator(0.5)) ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.1)) ax.set_title(”Multiple Locator”) plt.show() Output Fixed Locator The FixedLocator() places ticks at specified fixed locations. Example Here is an example of using the FixedLocator() class. # Fixed Locator fig, ax = plt.subplots(1,1,figsize=(7,1.5), facecolor=”#eaffff”) plt.subplots_adjust(bottom=0.3, top=0.6, wspace=0.2, hspace=0.4) draw_ticks(ax, title=”FixedLocator([0, 1, 3, 5])”) ax.xaxis.set_major_locator(ticker.FixedLocator([0, 1, 3, 5])) ax.xaxis.set_minor_locator(ticker.FixedLocator(np.linspace(0.2, 0.8, 4))) ax.set_title(”Fixed Locator”) plt.show() Output Linear Locator The LinearLocator spaces ticks evenly between specified minimum and maximum values. Example Here is an example that applies the Linear Locator to the major and minor ticks of an axes. # Linear Locator fig, ax = plt.subplots(1,1,figsize=(7,1.5), facecolor=”#eaffff”) plt.subplots_adjust(bottom=0.3, top=0.6, wspace=0.2, hspace=0.4) draw_ticks(ax, title=”LinearLocator(numticks=3)”) ax.xaxis.set_major_locator(ticker.LinearLocator(3)) ax.xaxis.set_minor_locator(ticker.LinearLocator(10)) ax.set_title(”Linear Locator”) plt.show() Output Index Locator This locator is suitable for index plots, where x = range(len(y)). Example Here is an example that uses the index loctator (ticker.IndexLocator() class). # Index Locator fig, ax = plt.subplots(1,1,figsize=(7,1.5), facecolor=”#eaffff”) plt.subplots_adjust(bottom=0.3, top=0.6, wspace=0.2, hspace=0.4) draw_ticks(ax, title=”IndexLocator(base=0.5, offset=0.25)”) ax.plot([0]*5, color=”white”) ax.xaxis.set_major_locator(ticker.IndexLocator(base=0.5, offset=0.25)) ax.set_title(”Index Locator”) plt.show() Output MaxN Locator The MaxNLocator finds up to a maximum number of intervals with ticks at nice locations. Example Here is an example of using the MaxNLocator() class for both major and minor ticks. # MaxN Locator fig, ax = plt.subplots(1,1,figsize=(7,1.5), facecolor=”#eaffff”) plt.subplots_adjust(bottom=0.3, top=0.6, wspace=0.2, hspace=0.4) draw_ticks(ax, title=”MaxNLocator(n=4)”) ax.xaxis.set_major_locator(ticker.MaxNLocator(4)) ax.xaxis.set_minor_locator(ticker.MaxNLocator(40)) ax.set_title(”MaxN Locator”) plt.show() Output Log Locator The LogLocator is used for spacing ticks logarithmically from min to max. Example Let”s see an example of using the Log Locator. It shows the minor tick labels on a log-scale. # Log Locator fig, ax = plt.subplots(1,1,figsize=(7,1.5), facecolor=”#eaffff”) plt.subplots_adjust(bottom=0.3, top=0.6, wspace=0.2, hspace=0.4) draw_ticks(ax, title=”LogLocator(base=10, numticks=15)”) ax.set_xlim(10**3, 10**10) ax.set_xscale(”log”) ax.xaxis.set_major_locator(ticker.LogLocator(base=10, numticks=15)) ax.set_title(”Log Locator”) plt.show() Output Print Page Previous Next Advertisements ”;