0
0
Matplotlibdata~5 mins

Multi-line text in Matplotlib

Choose your learning style9 modes available
Introduction

Multi-line text helps you add clear, organized labels or notes on your charts. It makes your graphs easier to understand by breaking long text into smaller parts.

You want to add a title with multiple lines to explain your chart.
You need to label parts of a graph with detailed descriptions.
You want to add a legend or annotation that has more than one sentence.
You want to display instructions or notes directly on the plot.
Syntax
Matplotlib
plt.text(x, y, 'Line 1\nLine 2\nLine 3', fontsize=12, color='blue')

Use \n inside the string to create new lines.

x and y set the position of the text on the plot.

Examples
This adds two lines of text centered at position (0.5, 0.5).
Matplotlib
plt.text(0.5, 0.5, 'Hello\nWorld', fontsize=14, ha='center')
This places three lines of red text near the top-left corner.
Matplotlib
plt.text(0.1, 0.9, 'Line 1\nLine 2\nLine 3', color='red')
Sample Program

This code draws a simple line plot and adds green multi-line text at the point (2, 5) on the graph.

Matplotlib
import matplotlib.pyplot as plt

plt.figure(figsize=(5, 3))
plt.plot([1, 2, 3], [4, 5, 6])

# Add multi-line text at position (2, 5)
plt.text(2, 5, 'This is line 1\nThis is line 2\nThis is line 3', fontsize=12, color='green')

plt.title('Example of Multi-line Text')
plt.show()
OutputSuccess
Important Notes

Make sure the text position (x, y) is inside the plot area to see the text.

You can customize font size, color, and alignment for better readability.

Summary

Use \n inside the text string to create multiple lines.

Position the text with x and y coordinates on the plot.

Multi-line text helps make your charts clearer and more informative.