How to Change the Number of Ticks in Matplotlib

How to Easily Customize the Number of Ticks on Your Matplotlib Plots

Effective data visualization relies heavily on clarity, and in the world of Matplotlib, controlling the appearance and placement of graph elements is paramount. One fundamental aspect of creating professional, readable plots is managing the axis ticks. Ticks are small markers that indicate where data values lie on the axis, providing crucial context for interpreting the visualization. When Matplotlib automatically determines tick placement, the results are often suitable, but specialized datasets or publication requirements may necessitate manual control over the number of visible ticks.

Fortunately, Matplotlib provides powerful tools to precisely adjust tick density. The most direct and flexible approach for automated tick control involves the use of the plt.locator_params() function. This function interacts directly with the underlying tick locators—the objects responsible for determining tick positions—allowing users to specify parameters like the maximum number of ticks desired. Understanding how to leverage this function, alongside other methods like plt.xticks() and plt.yticks() for manual specification, is essential for any advanced user of the library.

Beyond simple tick counting, we can also influence tick placement by defining the plotting boundaries. Methods like plt.xlim() and plt.ylim() are instrumental in setting the lower and upper limits of the plot axes. By constraining the data range displayed, we implicitly force the automatic tick generation process to operate only within those bounds, offering another layer of control over the resulting visual output. This article will thoroughly explore these techniques, demonstrating practical applications using the powerful Python environment.


Understanding Tick Locators and Parameters

In Matplotlib, the placement of major and minor ticks is governed by objects called Locators. When you create a plot, Matplotlib automatically assigns a default Locator to each axis, which usually tries to select “nice” tick positions based on the data range. However, for precise control over the number of ticks—rather than their specific numerical positions—we must interact with the parameters of this underlying Locator object. The function plt.locator_params() serves as the perfect interface for this interaction, providing a high-level way to influence the auto-tick generation process without needing to dive into complex Locator classes directly.

The core mechanism for specifying the desired number of ticks is through the use of the nbins argument within plt.locator_params(). The term nbins stands for “number of bins,” but in this context, it effectively dictates the maximum number of intervals (and thus, the ticks) that Matplotlib should attempt to display. It is important to note that nbins serves as a suggestion, not a strict command. Matplotlib’s Locators will use this value to guide their selection process, often choosing the closest aesthetically pleasing number of ticks that is equal to or slightly less than the requested nbins value, ensuring that the labels remain clean and non-overlapping.

To use this method effectively, you must specify which axis you intend to modify using the axis parameter, which accepts values of 'x' or 'y'. This allows for independent control over the horizontal and vertical scales, a necessity when data ranges differ significantly between the axes. By combining the axis parameter with the nbins parameter, we gain granular control over the tick density, improving the plot’s focus. The following syntax illustrates the fundamental implementation required to adjust the tick count on either axis:

You can use the following syntax to change the number of ticks on each axis in Matplotlib:

#specify number of ticks on x-axis
plt.locator_params(axis='x', nbins=4)

#specify number of ticks on y-axis
plt.locator_params(axis='y', nbins=2) 

The nbins argument specifies how many ticks to display on each axis.

The Role of the nbins Argument

The nbins parameter is the key component when using plt.locator_params() to manage tick count. It is crucial to internalize that nbins does not guarantee the exact number of ticks, but rather sets an upper limit on the number of intervals the Locator should aim for. For instance, if you request nbins=7 for a range of 0 to 100, Matplotlib might decide that five ticks (at 0, 25, 50, 75, 100) are cleaner and more readable than seven ticks, or it might successfully generate seven if the range is perfectly suited for division.

When selecting a value for nbins, consider the density and range of your data. If your data spans a vast numerical range, requesting a very small nbins value might lead to large, uninformative gaps between ticks. Conversely, requesting a very high nbins value for a limited range might cause tick labels to overlap, making the graph cluttered and illegible. The power of plt.locator_params() lies in its ability to balance the user’s request (via nbins) with Matplotlib’s built-in heuristics for clean visualization.

It is generally recommended to use nbins when you want to reduce visual complexity or ensure a plot has a consistent level of detail across multiple subplots. For example, if you are plotting several datasets with similar characteristics, fixing nbins ensures that viewers can compare the plots easily without distractions from varying tick densities. The value assigned to nbins should always be an integer greater than zero, representing the maximum number of major tick intervals (which is roughly the number of ticks minus one) desired on the specified axis.

The following examples show how to use this syntax in practice.

Alternative Methods: Manual Tick Placement

While plt.locator_params() is excellent for automatic, optimized control, there are scenarios where absolute precision is required, demanding that ticks appear at specific, custom numerical locations. For such cases, Matplotlib provides the plt.xticks() and plt.yticks() functions. These methods bypass the automated locator system entirely and allow the user to provide an explicit list of values where ticks should be drawn.

The primary advantage of using plt.xticks() or plt.yticks() is the guarantee of tick placement. If you pass a list of four numbers, you will get exactly four ticks at those specific coordinate points. This is particularly useful when dealing with categorical data, where the x-axis represents non-numerical labels, or when highlighting specific milestones or thresholds within the data range. These functions can also accept an optional second argument—a list of strings—to define custom labels for those ticks, offering superior flexibility for presentation.

However, this manual control comes with a caveat: the responsibility for avoiding overlapping labels and ensuring tick readability falls entirely on the developer. If the specified tick locations are too close together, or if the range is large, manual placement can quickly result in a cluttered plot. Therefore, these methods are best suited for smaller datasets or highly specialized visualizations where every tick location is predetermined and justified, complementing the automated control offered by plt.locator_params().

Controlling Plot Boundaries with plt.xlim() and plt.ylim()

Another indirect yet powerful way to influence the number and position of ticks is by explicitly defining the viewing window of the plot using plt.xlim() and plt.ylim(). These functions establish the minimum and maximum data values that will be visible on the x and y axes, respectively. While their primary role is framing the data, they inherently constrain the range over which the Matplotlib Locators operate.

When the range is artificially constrained—for example, forcing the x-axis to run from 0 to 10 even though the data extends to 20—the automatic Locators will only generate ticks within the visible 0-10 window. If the original data range led to 10 ticks, zooming in using plt.xlim() might reduce the required number of ticks to maintain a consistent interval size, thereby achieving a change in the displayed tick count without directly manipulating nbins. This technique is especially useful for focusing on specific sections of a plot where data density is highest.

These boundary setting functions require two numerical inputs: the lower limit and the upper limit. By carefully selecting these limits, you not only frame the visualization but also implicitly guide the tick generation algorithm. This method is often used in conjunction with plt.locator_params(): first, you set the precise boundaries using plt.ylim(), and then you fine-tune the tick density within those boundaries using the nbins argument, offering a highly tailored approach to axis formatting.

Example 1: Specify Number of Ticks on Both Axes

This initial example demonstrates the most comprehensive application of the plt.locator_params() method, where we seek to control the tick density simultaneously on both the horizontal (x) and vertical (y) axes. We begin by importing the necessary library, matplotlib.pyplot, typically aliased as plt. We then define a simple dataset consisting of four points. The goal is to plot this data and enforce a specific, low number of ticks to ensure maximum visual clarity, which is often desirable in reports or presentations where minimal grid lines are preferred.

In the code block below, notice the definition of the data points x and y. After calling plt.plot(x, y) to render the line graph, we introduce the two critical calls to plt.locator_params(). For the x-axis, we set nbins=4, requesting that Matplotlib select approximately four ticks suitable for the range [1, 4]. For the y-axis, which spans a larger range [7, 24], we intentionally set nbins=2, forcing the locator to be highly restrictive in tick placement, likely resulting in only the minimum and maximum labels.

The successful execution of this code demonstrates that plt.locator_params() is highly effective for global tick control across a plot. By setting nbins differently for each axis, we achieve an asymmetric visualization that prioritizes detail on the x-axis while simplifying the y-axis presentation. This technique is invaluable for managing plots where one dimension carries more critical granular information than the other, allowing the visualization to direct the viewer’s attention appropriately.

import matplotlib.pyplot as plt

#define data
x = [1, 2, 3, 4]
y = [7, 13, 24, 22]

#create plot
plt.plot(x, y, color='red')

#specify number of ticks on axes
plt.locator_params(axis='x', nbins=4)
plt.locator_params(axis='y', nbins=2)

Example 2: Specify Number of Ticks on X-Axis Only

Often, control is required only for a single dimension, leaving the other axis to utilize Matplotlib’s default automatic settings. In this example, we focus solely on regulating the density of the x-axis ticks. By calling plt.locator_params() and explicitly setting the axis='x' parameter, we instruct Matplotlib to modify only the horizontal axis Locator, ensuring that the vertical axis remains untouched and operates under its default configuration. This approach is beneficial when the x-axis represents time, categories, or index points that require specific demarcation, while the data values on the y-axis are adequately represented by the default intervals.

In this scenario, we maintain the same underlying dataset used in Example 1. However, the subsequent code only includes one call to plt.locator_params(). We set nbins=2 for the x-axis, which has a range from 1 to 4. This highly restrictive setting forces the x-axis to display significantly fewer ticks than the standard automatic placement would typically generate. By requesting only two bins, we are essentially asking for ticks near the minimum and maximum of the data range, providing a high-level view of the x-dimension.

Observing the output image confirms that the x-axis now displays only two principal ticks, significantly simplifying the visual field. Crucially, the y-axis, which spans from 7 to 24, retains its default tick placement. This highlights the modularity of the plt.locator_params() function; it allows for targeted modification without necessitating complex object manipulation or interference with the adjacent axis. This targeted control maintains the readability of the y-axis while forcing the desired clarity onto the x-axis.

import matplotlib.pyplot as plt

#define data
x = [1, 2, 3, 4]
y = [7, 13, 24, 22]

#create plot
plt.plot(x, y, color='red')

#specify number of ticks on x-axis
plt.locator_params(axis='x', nbins=2)

Example 3: Specify Number of Ticks on Y-Axis Only

Conversely to the previous demonstration, this example illustrates how to isolate control over the vertical axis using the same powerful function. Manipulating the y-axis ticks is often crucial when the vertical scale represents derived values, percentages, or metrics whose intervals need specific simplification or emphasis. By setting axis='y' within plt.locator_params(), we ensure that only the vertical Locator is engaged, thereby preserving the original, automatically generated ticks on the x-axis.

Using our consistent dataset, the y-axis ranges from 7 to 24. We specify nbins=2 for this axis, similar to our constraint in Example 1, but this time without touching the x-axis parameters. This action forces the Matplotlib Locator to seek the cleanest representation of the range [7, 24] using only two major tick intervals. Given the relatively complex range, the Locator will select values that best represent the span while keeping the total number of visible ticks minimal.

The resulting plot clearly shows the desired effect: the y-axis is significantly simplified, displaying only a couple of major ticks, while the x-axis maintains its default tick density, accurately labeling the values 1, 2, 3, and 4. This pattern of selective axis customization is a hallmark of professional plotting in Matplotlib, allowing developers and analysts to prioritize the visual information presented on the most critical axis of the plot. Utilizing these methods ensures that the final visualization is both accurate and optimized for the intended audience.

import matplotlib.pyplot as plt

#define data
x = [1, 2, 3, 4]
y = [7, 13, 24, 22]

#create plot
plt.plot(x, y, color='red')

#specify number of ticks on y-axis
plt.locator_params(axis='y', nbins=2)

Change number of ticks in Matplotlib

Summary of Tick Control Techniques

Mastering the control of axis ticks is a cornerstone of advanced Matplotlib usage. While the library is adept at generating reasonable defaults, customizing tick density is essential for tailoring visualizations to specific analytical or publication standards. We have primarily focused on three powerful and interrelated methods for achieving this customization.

First, the use of the plt.locator_params() function with the nbins argument provides the most efficient and scalable solution for guiding the automatic tick generation process. It allows the user to suggest a maximum number of ticks, maintaining readability by letting Matplotlib select the best numerical intervals. This approach should be the default choice when seeking to reduce clutter while still relying on optimized interval placement.

Second, for instances requiring absolute control over the numerical location of the ticks, the methods plt.xticks() and plt.yticks() are indispensable. These functions allow the user to define a precise list of tick coordinates and corresponding labels, making them ideal for categorical plotting or highlighting specific, non-uniform data points. It is crucial to use these methods judiciously, ensuring that manual placement does not lead to visual clutter.

Finally, we explored how boundary setting via plt.xlim() and plt.ylim() indirectly impacts tick generation by limiting the range available to the Locators. Utilizing these three families of functions in combination allows Python developers to produce highly refined, data-centric visualizations that convey information with maximum impact and clarity, moving beyond the standard defaults to create truly professional graphical outputs.

Best Practices for Tick Management

When implementing tick control in Matplotlib, adopting certain best practices can significantly enhance the quality of your visualizations. One primary consideration is ensuring that the number of ticks is proportional to the overall size of the plot and the complexity of the data being displayed. A large plot can handle more ticks without appearing cluttered, while a small embedded figure requires a minimal number of major ticks for immediate comprehension.

Furthermore, always prioritize numerical intervals that are easy for the viewer to interpret. Matplotlib’s Locators are designed to select “nice numbers” (e.g., multiples of 1, 2, 5, 10). When using nbins, if your requested count results in awkward decimal intervals, consider adjusting nbins slightly to guide the Locator toward cleaner values. If you must use complex intervals, utilizing plt.xticks() with custom string labels can ensure that the odd numerical values are clearly explained to the viewer.

A final best practice involves the integration of tick control with other visualization elements, such as grid lines. Ticks define the labeled markers, but grid lines extend those marks across the plot area. By limiting the number of ticks using plt.locator_params(), you naturally reduce the number of major grid lines, leading to a cleaner aesthetic. Remember that the goal of modifying ticks is not just numerical accuracy, but communicative efficiency; fewer, well-placed ticks often provide more clarity than an abundance of markers.

Cite this article

stats writer (2025). How to Easily Customize the Number of Ticks on Your Matplotlib Plots. PSYCHOLOGICAL SCALES. Retrieved from https://scales.arabpsychology.com/stats/how-to-change-the-number-of-ticks-in-matplotlib/

stats writer. "How to Easily Customize the Number of Ticks on Your Matplotlib Plots." PSYCHOLOGICAL SCALES, 4 Dec. 2025, https://scales.arabpsychology.com/stats/how-to-change-the-number-of-ticks-in-matplotlib/.

stats writer. "How to Easily Customize the Number of Ticks on Your Matplotlib Plots." PSYCHOLOGICAL SCALES, 2025. https://scales.arabpsychology.com/stats/how-to-change-the-number-of-ticks-in-matplotlib/.

stats writer (2025) 'How to Easily Customize the Number of Ticks on Your Matplotlib Plots', PSYCHOLOGICAL SCALES. Available at: https://scales.arabpsychology.com/stats/how-to-change-the-number-of-ticks-in-matplotlib/.

[1] stats writer, "How to Easily Customize the Number of Ticks on Your Matplotlib Plots," PSYCHOLOGICAL SCALES, vol. X, no. Y, ص Z-Z, December, 2025.

stats writer. How to Easily Customize the Number of Ticks on Your Matplotlib Plots. PSYCHOLOGICAL SCALES. 2025;vol(issue):pages.

Download Post (.PDF)
Slide Up
x
PDF
Scroll to Top