Learning Matplotlib: Customizing the Number of Ticks on Your Plots


Effective Data Visualization hinges on meticulous control over presentation elements. Among the most crucial components of any chart are the axis ticks, which serve as essential reference points for interpreting data scales. While the widely used plotting library, Matplotlib, typically employs sophisticated automatic algorithms for tick placement, there are frequent instances—especially when dealing with complex or highly dense datasets—where the default settings can result in visual clutter or inadequate resolution. Customizing the frequency and number of these marks is paramount for achieving a clean, professional aesthetic.

Fortunately, Matplotlib offers a powerful and straightforward utility specifically designed for this purpose: the plt.locator_params function. This function grants developers the ability to explicitly suggest a maximum density for the axis ticks, allowing for fine-grained control over the plot’s appearance without requiring complex knowledge of Matplotlib’s underlying locator classes. This article will guide you through using locator_params to manage tick density effectively.

To adjust the suggested maximum number of ticks on either the X or Y axis in Matplotlib, you utilize the following command syntax. This provides an immediate way to enforce specific visual constraints on your plots:

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

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

The critical component of this function is the nbins argument. This parameter specifies the desired number of major intervals, which directly influences the resulting number of tick marks displayed on the selected axis (specified by the axis parameter). It is essential to remember that nbins acts as a strong suggestion to the internal Matplotlib tick locator algorithm; the algorithm may slightly adjust the final count to ensure that the resulting intervals are mathematically clean, aesthetically pleasing, and feature easy-to-read numerical labels.

Understanding the locator_params Function

Matplotlib relies on sophisticated internal objects known as locators to intelligently determine the optimal placement of tick marks. When we invoke plt.locator_params, we are essentially overriding the dynamic settings provided by the default auto-locator. This function is a high-level wrapper that simplifies interaction with these underlying mechanisms, requiring only two crucial parameters for managing tick count: axis and nbins.

The axis parameter is straightforward, accepting either 'x' or 'y' to target the horizontal or vertical axis, respectively. This targeted approach is critical for maintaining clarity, particularly in complex visualizations or multi-panel figures where different axes may require vastly different levels of detail. By isolating the adjustment to a single dimension, we prevent unintended scaling or cosmetic changes to the other dimension of the plot.

While the end goal is controlling the number of visible ticks, the nbins argument defines the number of major intervals or “bins” the locator should aim for. For example, setting nbins to 6 instructs the system to divide the axis range into approximately six legible sections. The locator then ensures that the resulting numerical labels are “nice” numbers (e.g., 0, 10, 20, 30) instead of awkward fractional values, significantly improving the readability and professional quality of the chart.

Controlling Both Axes: A Comprehensive Example

The most frequent application of tick customization involves simultaneously adjusting the tick density on both the X and Y axes to achieve a balanced, clutter-free visualization. This approach is recommended when the default automatic spacing results in overcrowding along both dimensions, making the plot illegible or difficult to interpret quickly. We demonstrate this common use case below using a simple line plot derived from a small dataset.

To initiate the process, we use the standard Python import statement to access the necessary plotting capabilities via matplotlib.pyplot as plt. After defining our small dataset (represented by the x and y lists), we generate the plot. The crucial step follows, where we apply plt.locator_params twice—once for the X-axis and once for the Y-axis—to enforce our specific density requirements.

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)

In the resulting visualization, the X-axis is constrained to display four ticks, aligning perfectly with our four discrete data points (1, 2, 3, 4). Simultaneously, the Y-axis is instructed to use only two major intervals. As confirmed by the image below, Matplotlib successfully interprets these suggestions, resulting in a significantly cleaner vertical scale and validating the effectiveness of using locator_params for simultaneous axis control.

Targeted Control: X-Axis and Y-Axis Specific Adjustments

Often, visual issues are confined to a single axis. For instance, the X-axis might represent dates or numerous categories, causing labels to overlap, while the Y-axis might be perfectly scaled by Matplotlib’s default settings. In such instances, applying locator_params exclusively to the horizontal axis is the ideal, non-disruptive solution. This approach ensures maximal cleanup where it is needed most, preserving the automated optimization on the other dimension.

The following code demonstrates how to reduce visual noise solely along the bottom of the chart. By defining the data and plot structure identically to the previous example but only applying the instruction for axis='x' with a reduced nbins value, we instruct the locator to simplify the horizontal scale dramatically. Crucially, the Y-axis is left untouched, relying on the default algorithm to handle the range between 7 and 24.

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 maximum number of ticks on x-axis
plt.locator_params(axis='x', nbins=2)

By setting nbins=2 for the X-axis, we drastically reduce the visual noise along the bottom of the chart. This technique is particularly valuable when the X-axis represents a continuous, rather than categorical, variable, allowing the reader to focus on the overall trend rather than specific, highly dense labels. Reviewing the corresponding figure confirms that the Y-axis retains its optimal default tick placement.

Conversely, we might need to simplify the vertical scale when the data range is expansive or when only major reference points are necessary. By setting axis='y', we isolate the tick reduction to the vertical dimension. This technique significantly improves the visual impact of the data’s magnitude shifts, ensuring the reader focuses on the overall trend without distraction from overly dense vertical grid lines. The X-axis retains its default spacing, ensuring sequential or temporal details are not obscured.

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 maximum number of ticks on y-axis
plt.locator_params(axis='y', nbins=2)

By executing this code, we observe that the X-axis maintains its default tick allocation (likely showing all four integer values), while the Y-axis is simplified to only two major tick labels. This simplification is highly effective for charts displayed in presentations or reports where rapid interpretation of the vertical scale is critical.

Change number of ticks in Matplotlib

Advanced Considerations and Best Practices

While the plt.locator_params function provides robust and simple control over axis density, developers must exercise caution and judgment when applying custom settings. The core purpose of customizing ticks must always be to improve the clarity and legibility of the Data Visualization, not merely to minimize the number of labels. Over-simplification can lead to loss of crucial detail, making it harder for the audience to accurately estimate specific values or subtle shifts in the data.

When determining the optimal value for the nbins argument, several contextual factors should influence your decision. First, always prioritize Readability: the resulting tick labels should be “nice” numbers—clean integers or multiples (e.g., 0, 50, 100)—that logically fit the scale. Second, consider the Data Range: if the data spans a small numerical range, an excessively high nbins value will force unnecessary granularity, while an overly low value might obscure critical differences.

Finally, the Plot Context and Size are important determinants. Plots embedded in small dashboards or reports inherently benefit from fewer ticks to avoid visual clutter. Conversely, large, high-resolution figures designed for detailed analysis can often accommodate a greater number of reference points. Mastering these contextual trade-offs is key to creating publication-ready graphics using Matplotlib.

For users who require control beyond the capabilities of the high-level locator_params function, it is beneficial to understand the underlying architecture. Matplotlib utilizes dedicated locator classes, such as MaxNLocator, which locator_params employs internally. Exploring these classes offers the ultimate level of customization, enabling precise control over both major and minor tick placements and formatting. However, for most practical applications requiring simple density management, plt.locator_params remains the most efficient and effective tool.

Additional Resources for Matplotlib Mastery

To further refine your ability to produce high-quality visualizations, we highly recommend exploring the comprehensive official documentation on Matplotlib’s locators and formatters. These resources detail how to manage not just the placement, but also the style, rotation, and labeling of axis elements, ensuring your data presentation is both accurate and visually compelling.

Cite this article

Mohammed looti (2025). Learning Matplotlib: Customizing the Number of Ticks on Your Plots. PSYCHOLOGICAL STATISTICS. Retrieved from https://statistics.arabpsychology.com/change-the-number-of-ticks-in-matplotlib/

Mohammed looti. "Learning Matplotlib: Customizing the Number of Ticks on Your Plots." PSYCHOLOGICAL STATISTICS, 3 Nov. 2025, https://statistics.arabpsychology.com/change-the-number-of-ticks-in-matplotlib/.

Mohammed looti. "Learning Matplotlib: Customizing the Number of Ticks on Your Plots." PSYCHOLOGICAL STATISTICS, 2025. https://statistics.arabpsychology.com/change-the-number-of-ticks-in-matplotlib/.

Mohammed looti (2025) 'Learning Matplotlib: Customizing the Number of Ticks on Your Plots', PSYCHOLOGICAL STATISTICS. Available at: https://statistics.arabpsychology.com/change-the-number-of-ticks-in-matplotlib/.

[1] Mohammed looti, "Learning Matplotlib: Customizing the Number of Ticks on Your Plots," PSYCHOLOGICAL STATISTICS, vol. X, no. Y, ص Z-Z, November, 2025.

Mohammed looti. Learning Matplotlib: Customizing the Number of Ticks on Your Plots. PSYCHOLOGICAL STATISTICS. 2025;vol(issue):pages.

Download Post (.PDF)
Scroll to Top