Skill - Set axes ticks and tick labels in matplotlib
Skills Required
- Setup python development environment
- Basic Printing in Python
- Commenting in Python
- Managing Variables in python
- Introduction to Matplotlib plotting library
- Styling Matplotlib plots
Please make sure to have all the skills mentioned above to understand and execute the code mentioned below. Go through the above skills if necessary for reference or revision
Matplotlib is a plotting library tn the scipy ecosystem of libraries.
Please make sure that you covered thepost on basics
Sometimes we may desire to control the location of axis ticks of our subplots. This can be achieved by using the set_xticks
and set_yticks
functions of the axes handle.
Example - specify the position of axis ticks using set_xticks
and set_yticks
import matplotlib.pyplot as plt
x = [0,1,2,3,4,5,6,7,8]
y = [8,6,4,2,9,7,6,3,1]
# create a plotting area and get the figure, axes handle in return
fig, ax = plt.subplots()
# plot data on the axes handle
ax.plot(x, y)
# specify the position of x axis ticks
ax.set_xticks([0,2,4,6,8])
# specify the position of y axis ticks
ax.set_yticks([0,3,6,9])
# print the plot
plt.show()
In order to use custom tick labels instead of default tick labels, we can use set_xticklabels
and set_yticklabels
functions of the axes handle
Example - specify the axis labels using set_xticklabels
and set_yticklabels
import matplotlib.pyplot as plt
x = [0,1,2,3,4,5,6,7,8]
y = [8,6,4,2,9,7,6,3,1]
# create a plotting area and get the figure, axes handle in return
fig, ax = plt.subplots()
# plot data on the axes handle
ax.plot(x, y)
# specify the position of x axis ticks
ax.set_xticks([0,2,4,6,8])
# specify the tick labels of x axis
ax.set_xticklabels(['zero','two','four','six','eight'])
# specify the position of y axis ticks
ax.set_yticks([0,3,6,9])
# print the plot
plt.show()
Example - avoid axis ticks by specifying empty array
import matplotlib.pyplot as plt
x = [0,1,2,3,4,5,6,7,8]
y = [8,6,4,2,9,7,6,3,1]
# create a plotting area and get the figure, axes handle in return
fig, ax = plt.subplots()
# plot data on the axes handle
ax.plot(x, y)
# provide empty array to specify that x axis ticks not required
ax.set_xticks([])
# print the plot
plt.show()
Video
You can the video on this post here
Online Interpreter
Although we recommend to practice the above examples in Visual Studio Code, you can run these examples online at https://pynative.com/online-python-code-editor-to-execute-python-code/
References
- official documentation on set axis ticks - https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.axes.Axes.set_xticks.html#matplotlib.axes.Axes.set_xticks
- another post - https://www.tutorialspoint.com/matplotlib/matplotlib_setting_ticks_and_tick_labels.htm
- another post - https://jakevdp.github.io/PythonDataScienceHandbook/04.10-customizing-ticks.html
Comments
Post a Comment