Consider the following Python code using matplotlib. What will be the text displayed on the plot?
import matplotlib.pyplot as plt fig, ax = plt.subplots() text = "Line 1\nLine 2\nLine 3" ax.text(0.5, 0.5, text, ha='center', va='center') plt.show()
Think about how matplotlib handles newline characters in text strings.
Matplotlib interprets the newline character \n as a line break, so the text is shown on multiple lines stacked vertically.
Look at this code snippet:
import matplotlib.pyplot as plt fig, ax = plt.subplots() text = 'First line\nSecond line\nThird line' ax.text(0.5, 0.5, text, ha='center', va='center', wrap=True) plt.show()
Why might the text not wrap or display as expected?
Check the official documentation for ax.text parameters.
The wrap parameter is not a valid argument for ax.text. Newlines in the string handle line breaks, but wrapping long lines automatically is not supported here.
plt.text with custom line spacing?Given the goal to display multi-line text with extra space between lines, which code snippet achieves this?
Check the exact parameter name for line spacing in plt.text.
The correct parameter to control line spacing in matplotlib text is linespacing. Other options are invalid and cause errors.
When using multi-line text in matplotlib, how does the ha (horizontal alignment) parameter affect the text?
Think about how each line is positioned horizontally.
The ha parameter aligns each line individually relative to the x coordinate, so all lines share the same horizontal alignment.
Given this code, what is the approximate bounding box width and height of the multi-line text in display units?
import matplotlib.pyplot as plt fig, ax = plt.subplots() text_obj = ax.text(0.5, 0.5, 'Hello\nWorld', ha='center', va='center', fontsize=12) fig.canvas.draw() bbox = text_obj.get_window_extent() width, height = bbox.width, bbox.height print(round(width), round(height))
Remember that width is usually larger than height for horizontal text, and multi-line text height increases with lines.
The bounding box width is roughly the width of the longest line in pixels (~60), and height is roughly the height of two lines (~30) at fontsize 12.