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
Selected Reading
How to autosize text in matplotlib Python?
To autosize text in matplotlib, you can use several approaches including tight_layout(), figure.autolayout, and adjusting text rotation. These methods help prevent text overlap and ensure proper spacing.
Method 1: Using figure.autolayout
The figure.autolayout parameter automatically adjusts subplot parameters to fit the figure area ?
import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True plt.plot(range(10)) labels = [7 * str(i) for i in range(10)] plt.xticks(range(10), labels, rotation=30) plt.show()
Method 2: Using tight_layout()
The tight_layout() method automatically adjusts subplot parameters to prevent overlapping ?
import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(8, 4)) ax.plot(range(10)) labels = ['Long Label ' + str(i) * 3 for i in range(10)] ax.set_xticks(range(10)) ax.set_xticklabels(labels, rotation=45) plt.tight_layout() plt.show()
Method 3: Using constrained_layout
The constrained_layout provides better automatic spacing than tight_layout() ?
import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(8, 4), constrained_layout=True) data = [10, 25, 30, 55, 40, 65, 75, 85, 90, 95] ax.bar(range(10), data) labels = ['Category_' + str(i) + '_Extended' for i in range(10)] ax.set_xticks(range(10)) ax.set_xticklabels(labels, rotation=45, ha='right') plt.show()
Adjusting Font Size Automatically
You can also adjust font size based on the number of labels ?
import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(10, 5)) data = range(20) ax.plot(data) labels = ['Label_' + str(i) for i in data] fontsize = max(6, 12 - len(labels) // 5) # Reduce font size for more labels ax.set_xticks(data) ax.set_xticklabels(labels, rotation=45, fontsize=fontsize) plt.tight_layout() plt.show()
Comparison
| Method | When to Use | Advantages |
|---|---|---|
figure.autolayout |
Simple plots | Automatic, set once globally |
tight_layout() |
Most cases | Fine control, works well |
constrained_layout |
Complex subplots | Better spacing algorithm |
Conclusion
Use tight_layout() for most cases as it provides good automatic spacing. For complex plots with multiple subplots, constrained_layout=True offers better results.
Advertisements
