Hey folks! This paper will show you how to rotate the tick labels in Matplotlib plots in Python.
Ticks are the values that represent data points on axes. Matplotlib automatically marks the data points on the axes, but it also allows us to create our own axes with ticks and tick labels of our own.
Rotate Tick Labels in Matplotlib
We begin by creating a normal plot and for this tutorial, we will be building the sine plot using some random x angles and plot sine values of the x values as y values.
import matplotlib.pyplot as plt import numpy as np plt.style.use('seaborn') x = [0, 90, 180, 270, 360] y = np.sin(x) plt.plot(x,y) plt.show()
Rotating the Ticks by 45deg
Let’s have a look at how to rotate the x and y axes. To modify the axis level in the graph plot, we utilize
yticks(). Both were utilized to adjust the axis independently in this case.
import matplotlib.pyplot as plt import numpy as np plt.style.use('seaborn') x = [0, 90, 180, 270, 360] y = np.sin(x) plt.plot(x,y) plt.xticks(rotation = 45) plt.yticks(rotation = 45) plt.show()
As you may notice above, the tick labels (numbers) on both the axes are now tilted to 45deg. You can play around with the number to tilt them further.
Rotate Tickets By 90deg
Another method for rotating ticks is to use
tick params() to rotate both axes at the same time without using individual statements.
x = [0, 90, 180, 270, 360] y = num.sin(x) plt.plot(x,y) ln = plt.gca() ln.tick_params(axis='both', labelrotation = 90) plt.show()
Congratulations! You just learned how to rotate tick labels in matplotlib plots using two different methods. Hope you enjoyed it! 😇
Liked the tutorial? In any case, I would recommend you to have a look at the tutorials mentioned below:
- Plot Mathematical Functions – How to Plot Math Functions in Python?
- Plot data from Excel Sheet using Python
- 3 Matplotlib Plotting Tips to Make Plotting Effective
- Python: Plotting Smooth Curves
Thank you for taking your time out! Hope you learned something new!! 😄