0
0
Matplotlibdata~10 mins

Image extent and aspect ratio in Matplotlib - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to display an image using matplotlib's imshow function.

Matplotlib
import matplotlib.pyplot as plt
import numpy as np

image = np.random.rand(5,5)
plt.imshow(image, extent=[1])
plt.show()
Drag options to blanks, or click blank then click option'
A[1, 5, 1, 5]
B[0, 5, 0, 5]
C[0, 1, 0, 1]
D[0, 10, 0, 10]
Attempts:
3 left
💡 Hint
Common Mistakes
Using extent values that don't match the image size, causing distortion.
Forgetting that extent expects [xmin, xmax, ymin, ymax].
2fill in blank
medium

Complete the code to set the aspect ratio of the image to 'equal' so pixels are square.

Matplotlib
import matplotlib.pyplot as plt
import numpy as np

image = np.random.rand(5,10)
plt.imshow(image, extent=[0, 10, 0, 5])
plt.gca().set_aspect([1])
plt.show()
Drag options to blanks, or click blank then click option'
A'equal'
B'auto'
C'square'
D'free'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'auto' which lets matplotlib stretch the image to fill the axes.
Using invalid aspect values like 'square' or 'free'.
3fill in blank
hard

Fix the error in the code to correctly display the image with the specified extent and aspect ratio.

Matplotlib
import matplotlib.pyplot as plt
import numpy as np

image = np.random.rand(3,6)
plt.imshow(image, extent=[0, 6, 0, 3])
plt.gca().set_aspect([1])
plt.show()
Drag options to blanks, or click blank then click option'
A'none'
B'auto'
C'equal'
D1.0
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'none' which is not a valid aspect value.
Using 'auto' which stretches the image.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that maps words to their lengths only if the length is greater than 3.

Matplotlib
words = ['data', 'science', 'ai', 'ml', 'python']
lengths = {word: [1] for word in words if [2] }
Drag options to blanks, or click blank then click option'
Alen(word)
Blen(word) > 3
Cword
Dlen(word) < 3
Attempts:
3 left
💡 Hint
Common Mistakes
Using the word itself as the value instead of its length.
Using the wrong condition like length less than 3.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps uppercase words to their lengths only if length is greater than 2.

Matplotlib
words = ['cat', 'dog', 'a', 'elephant']
[1] = { [2]: [3] for word in words if len(word) > 2 }
print([1])
Drag options to blanks, or click blank then click option'
Alengths
Bword.upper()
Clen(word)
Dwords
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong variable name or missing the assignment.
Using the word itself instead of uppercase for keys.
Using the word instead of length for values.