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
Putting a newline in Matplotlib label with TeX in Python
When creating plots with Matplotlib, you may need to add newlines to axis labels for better formatting. This is easily achieved using the \n escape character in your label strings.
Basic Example with Newlines in Labels
Here's how to add newlines to both X and Y axis labels ?
import matplotlib.pyplot as plt
# Create simple data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# Plot with newlines in labels
plt.plot(x, y, 'b-', linewidth=2)
plt.ylabel("Y-axis \n with newline")
plt.xlabel("X-axis \n with newline")
plt.title("Plot with Newlines in Labels")
plt.show()
Advanced Example with Multiple Lines and Colors
You can combine newlines with color cycling for more complex visualizations ?
import matplotlib.pyplot as plt
from cycler import cycler
# Set up labels with newlines
plt.ylabel("Y-axis \n with newline")
plt.xlabel("X-axis \n with newline")
# Configure color cycling
plt.rc('axes', prop_cycle=(cycler('color', ['r', 'g', 'b', 'y'])))
# Plot multiple lines with different colors
plt.plot([0, 5], label='Line 1')
plt.plot([2, 6], label='Line 2')
plt.plot([3, 8], label='Line 3')
plt.plot([4, 9], label='Line 4')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()
Using TeX Formatting with Newlines
When using TeX formatting, you can combine mathematical expressions with newlines ?
import matplotlib.pyplot as plt import numpy as np # Enable TeX rendering plt.rcParams['text.usetex'] = True x = np.linspace(0, 2*np.pi, 100) y = np.sin(x) plt.plot(x, y) plt.xlabel(r'$\theta$ \n (radians)') plt.ylabel(r'$\sin(\theta)$ \n amplitude') plt.title(r'Sine Wave \n with TeX labels') plt.show()
Key Points
Use
\nto insert newlines in any Matplotlib label stringThe
cyclerclass allows automatic color rotation for multiple plotsTeX formatting can be combined with newlines using
plt.rcParams['text.usetex'] = TrueNewlines work in titles, axis labels, and legend entries
Conclusion
Adding newlines to Matplotlib labels improves readability and formatting. Use \n in any label string, and combine with TeX formatting or color cycling for professional-looking plots.
