4. Identify the error in this interactive plot code snippet:
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
fig, ax = plt.subplots()
x = range(5)
y = [i*2 for i in x]
line, = ax.plot(x, y)
slider_ax = plt.axes([0.25, 0.1, 0.65, 0.03])
slider = Slider(slider_ax, 'Multiplier', 1, 5, valinit=1)
def update(val):
line.set_ydata([i*val for i in x])
fig.canvas.draw_idle()
# Missing slider.on_changed(update)
plt.show()
medium
A. The slider range is invalid and causes a runtime error.
B. The plot will raise a syntax error due to missing parentheses.
C. The plot will update but with wrong y-values.
D. The slider will not update the plot because the event connection is missing.
Solution
Step 1: Check slider event connection
The code does not call slider.on_changed(update), so update is never triggered.
Step 2: Understand effect of missing connection
Without this, moving the slider won't change the plot.
Final Answer:
The slider will not update the plot because the event connection is missing. -> Option D
Quick Check:
Missing on_changed = no update [OK]
Hint: Always connect slider with on_changed(update) [OK]
Common Mistakes:
Assuming plot updates without event connection
Thinking missing parentheses cause syntax error
Believing slider range causes error
5. You want to explore a dataset's distribution interactively by adjusting the number of bins in a histogram using a slider. Which approach best uses matplotlib interactivity to achieve this?
hard
A. Create multiple static histograms with different bins and switch between them manually.
B. Create a slider controlling bin count; update histogram bars on slider change.
C. Use a slider to change the color of the histogram bars only.
D. Save separate histogram images for each bin count and display them one by one.
Solution
Step 1: Identify interactive control needed
Adjusting bin count dynamically requires a slider controlling the number of bins.
Step 2: Implement update on slider change
On slider movement, redraw the histogram with the new bin count to explore distribution.
Final Answer:
Create a slider controlling bin count; update histogram bars on slider change. -> Option B
Quick Check:
Slider controls bins, updates histogram [OK]
Hint: Use slider to change bins and redraw histogram [OK]
Common Mistakes:
Using static plots instead of interactive updates
Changing only colors without affecting bins
Saving images instead of interactive plotting
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.