How to Rotate X-Axis Tick Label Text in Matplotlib?

How to Rotate X-Axis Tick Label Text in Matplotlib?

In Matplotlib, you can rotate the x-axis tick label text using the xticks() function and the rotation parameter. Here's how you can do it:

1. Basic Example:

Using the plt.xticks() function, you can set the rotation angle for the x-axis tick labels:

import matplotlib.pyplot as plt # Sample data x = ['Label1', 'Label2', 'Label3', 'Label4', 'Label5'] y = [1, 3, 5, 2, 4] plt.bar(x, y) # Rotate x-axis tick labels by 45 degrees plt.xticks(rotation=45) plt.show() 

2. Using Axes Object:

If you're using the object-oriented API, you can set the rotation on the Axes object:

fig, ax = plt.subplots() ax.bar(x, y) # Rotate x-axis tick labels by 45 degrees ax.set_xticks(x) ax.set_xticklabels(x, rotation=45) plt.show() 

3. Customizing the Alignment:

You can also adjust the alignment of the rotated labels using the ha parameter (horizontal alignment). This can be particularly useful when the rotation angle is set to 90 degrees:

plt.bar(x, y) # Rotate x-axis tick labels by 90 degrees and align them right plt.xticks(rotation=90, ha='right') plt.show() 

Adjusting the rotation of x-axis tick labels can help improve the readability of your plots, especially when dealing with long labels or a large number of ticks.


More Tags

ubuntu-10.04 statefulwidget pinchzoom torch uiwebviewdelegate checkstyle nsnumberformatter virtual-keyboard formatting jtable

More Programming Guides

Other Guides

More Programming Examples