How to Rotate X-Axis Tick Label Text in Matplotlib?
Matplotlib is an amazing and one of the most widely used data visualization libraries in Python for plots of arrays. It is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It is much popular because of its customization options as we can tweak about any element from its hierarchy of objects.
Rotating X-axis labels in Matplotlib
To rotate X-axis labels, there are various methods provided by Matplotlib i.e. change it on the Figure-level or by changing it on an Axes-level or individually by using built-in functions. Some methods are listed below :
Let’s create a simple line plot which we will modify further
Python3
import matplotlib.pyplot as plt
import numpy as np
x = np.arange( 0 , np.pi * 2 , 0.05 )
y = np.sin(x * * 2 )
plt.plot(x, y)
plt.title( 'Simple Example' )
plt.show()
|
Output :
Rotate X-Axis Tick Label Text using plt.xticks()
In this example, we will rotate X-axis labels on Figure-level using plt.xticks().
Syntax: matplotlib.pyplot.xticks(ticks=None, labels=None, **kwargs)
Python3
import matplotlib.pyplot as plt
import numpy as np
x = np.arange( 0 , np.pi * 2 , 0.05 )
y = np.sin(x * * 2 )
plt.plot(x, y)
plt.xticks(rotation = 25 )
plt.title( 'Rotating using plt.xticks()' )
plt.show()
|
Output :
Rotate X-Axis Tick Label Text using tick.set_rotation()
In this example, we will rotate X-axis labels on Axes-level using tick.set_rotation().
Syntax: Axes.get_xticks(self, minor=False)
Python3
import matplotlib.pyplot as plt
import numpy as np
x = np.arange( 0 , np.pi * 2 , 0.05 )
y = np.sin(x * * 2 )
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xticklabels(ax.get_xticks(), rotation = 50 )
plt.title( 'Rotating using tick.set_rotation()' )
plt.show()
|
Output:
Rotate X-Axis Tick Label Text using ax.set_xticklabels()
In this example, we will rotate X-axis labels individually by using the built-in ax.set_xticklabels() function.
Syntax: Axes.set_xticklabels(self, labels, fontdict=None, minor=False, **kwargs)
Python3
import matplotlib.pyplot as plt
import numpy as np
x = np.arange( 0 , np.pi * 2 , 0.05 )
y = np.sin(x * * 2 )
fig, ax = plt.subplots()
ax.plot(x, y)
for tick in ax.get_xticklabels():
tick.set_rotation( 75 )
plt.title( 'Rotating using ax.set_xticklabels()' )
plt.show()
|
Output:
Rotate X-Axis Tick Label Text using ax.xtick_params() function
In this example, we will rotate X-axis labels individually by using the built-in ax.xtick_params() function.
Syntax: matplotlib.pyplot.tick_params(axis=’both’, **kwargs)
Python3
import matplotlib.pyplot as plt
import numpy as np
x = np.arange( 0 , np.pi * 2 , 0.05 )
y = np.sin(x * * 2 )
fig, ax = plt.subplots()
ax.plot(x, y)
ax.tick_params(axis = 'x' , labelrotation = 100 )
plt.title( 'Rotating using ax.xtick_params()' )
plt.show()
|
Output:
Last Updated :
30 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...