Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to append a single labeled tick to X-axis using matplotlib?
To append a single labeled tick to X-axis using matplotlib, you can use set_xticks() and set_xticklabels() methods to add a custom tick at any position on the axis.
Steps
Set the figure size and adjust the padding between and around the subplots.
Create x and y data points using numpy.
Plot x and y data points using plot() method.
Set xticks at a single point.
Set the tick label for single tick point.
To display the figure, use show() method.
Example
import numpy as np
import matplotlib.pyplot as plt
# Set the figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create x and y data points
x = np.linspace(-5, 5, 50)
y = np.sin(x)
# Plot x and y data points
fig, ax = plt.subplots(1, 1)
p = ax.plot(x, y)
# Set xticks at a point
ax.set_xticks([-1.075])
# Set xticklabels for the point
ax.set_xticklabels(["$\bf{It\ is -\!1.075\ label}$"])
# Display the plot
plt.show()
Output
It will produce the following output −
Adding Multiple Custom Ticks
You can also add multiple custom ticks by providing lists to both methods ?
import numpy as np import matplotlib.pyplot as plt # Create data x = np.linspace(-5, 5, 50) y = np.sin(x) # Plot fig, ax = plt.subplots(figsize=(8, 4)) ax.plot(x, y) # Add multiple custom ticks ax.set_xticks([-2, 0, 2]) ax.set_xticklabels(['Min Point', 'Zero', 'Max Point']) plt.show()
Conclusion
Use set_xticks() to specify tick positions and set_xticklabels() to set custom labels. This technique is useful for highlighting specific points or adding meaningful labels to your plots.
