0
0
Matplotlibdata~20 mins

Text placement with ax.text in Matplotlib - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Text Placement Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this matplotlib text placement code?

Consider the following code that places text on a plot using ax.text. What text will appear at coordinates (0.5, 0.5)?

Matplotlib
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.text(0.5, 0.5, 'Center', ha='center', va='center')
plt.close(fig)
print(ax.texts[0].get_text())
A"ha='center', va='center'"
B"Center"
C"0.5, 0.5"
D"center"
Attempts:
2 left
💡 Hint

Look at the third argument of ax.text. It is the string that will be displayed.

data_output
intermediate
2:00remaining
How many text objects are on the axes after this code?

After running the code below, how many text objects are present on the axes?

Matplotlib
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.text(0.1, 0.1, 'A')
ax.text(0.2, 0.2, 'B')
ax.text(0.3, 0.3, 'C')
plt.close(fig)
print(len(ax.texts))
A3
B2
C1
D0
Attempts:
2 left
💡 Hint

Each call to ax.text adds one text object to the axes.

visualization
advanced
2:00remaining
Which option shows the correct vertical alignment of text?

Given the code below, which option correctly describes the vertical alignment of the text?

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.text(0.5, 0.5, 'Text', va='top')
plt.close(fig)
AThe text is aligned so its top is at y=0.5
BThe text is aligned so its bottom is at y=0.5
CThe text is aligned so its center is at y=0.5
DThe text is aligned so its baseline is at y=0.5
Attempts:
2 left
💡 Hint

Vertical alignment va='top' means the top of the text is at the given y coordinate.

🧠 Conceptual
advanced
2:00remaining
What happens if you set ha='right' in ax.text?

In matplotlib, what does setting ha='right' do to the text placement?

AThe center of the text is placed at the x coordinate
BThe left edge of the text is placed at the x coordinate
CThe right edge of the text is placed at the x coordinate
DThe text is rotated 90 degrees
Attempts:
2 left
💡 Hint

Horizontal alignment ha='right' aligns the right edge of the text to the x coordinate.

🔧 Debug
expert
2:00remaining
What error does this code raise?

What error will this code raise?

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.text(0.5, 0.5, 'Hello', ha='middle')
plt.close(fig)
ANo error, text is placed with default alignment
BTypeError: text() got an unexpected keyword argument 'ha'
CSyntaxError: invalid syntax
DValueError: Invalid horizontal alignment
Attempts:
2 left
💡 Hint

Check the valid values for ha in matplotlib documentation.