Bird
Raised Fist0
SciPydata~20 mins

SciPy with Matplotlib for visualization - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
SciPy Visualization Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a Gaussian distribution plot code
What will be the output of this code snippet that plots a Gaussian distribution using SciPy and Matplotlib?
SciPy
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

x = np.linspace(-3, 3, 100)
y = norm.pdf(x, 0, 1)
plt.plot(x, y)
plt.title('Gaussian Distribution')
plt.xlabel('x')
plt.ylabel('Probability Density')
plt.show()
AA bar chart with bars increasing from left to right
BA horizontal line at y=1 across the x-axis range
CA line plot showing a bell-shaped curve centered at 0
DA scatter plot with random points scattered around zero
Attempts:
2 left
💡 Hint
Think about what the probability density function of a normal distribution looks like.
data_output
intermediate
2:00remaining
Resulting array from SciPy interpolation
Given the following code using SciPy's interp1d, what is the output array printed?
SciPy
import numpy as np
from scipy.interpolate import interp1d

x = np.array([0, 1, 2, 3])
y = np.array([0, 1, 4, 9])
f = interp1d(x, y)
print(f([1.5, 2.5]))
A[2.5 6.5]
B[1.5 2.5]
C[3.0 7.0]
D[1.0 4.0]
Attempts:
2 left
💡 Hint
Interp1d does linear interpolation between points.
visualization
advanced
2:30remaining
Identify the plot type from SciPy clustering output
This code performs hierarchical clustering and plots a dendrogram. What does the plot visually represent?
SciPy
import numpy as np
from scipy.cluster.hierarchy import dendrogram, linkage
import matplotlib.pyplot as plt

np.random.seed(0)
data = np.random.rand(5, 2)
linked = linkage(data, 'single')
dendrogram(linked, labels=['A', 'B', 'C', 'D', 'E'])
plt.title('Hierarchical Clustering Dendrogram')
plt.show()
AA heatmap of pairwise distances
BA scatter plot of the original data points
CA bar chart showing cluster sizes
DA tree diagram showing how data points cluster step-by-step
Attempts:
2 left
💡 Hint
Dendrograms show hierarchical relationships between clusters.
🔧 Debug
advanced
2:00remaining
Identify the error in SciPy curve fitting code
What error will this code raise when run?
SciPy
import numpy as np
from scipy.optimize import curve_fit

def model(x, a, b):
    return a * x + b

xdata = np.array([1, 2, 3, 4])
ydata = np.array([2, 4, 6, 8])

params, covariance = curve_fit(model, xdata, ydata, p0=[1])
ANo error, code runs successfully
BValueError: p0 must be of length 2 for two parameters
CRuntimeWarning: overflow encountered in multiply
DTypeError: model() missing 1 required positional argument
Attempts:
2 left
💡 Hint
Check the initial guess p0 length matches the number of parameters in the model.
🚀 Application
expert
3:00remaining
Choosing the correct SciPy function for statistical test visualization
You want to visualize the distribution of two independent samples and test if they come from the same distribution using SciPy and Matplotlib. Which approach below correctly combines the test and visualization?
AUse scipy.stats.ks_2samp to test, then plot both samples' histograms with plt.hist
BUse scipy.stats.ttest_ind to test, then plot a scatter plot of the samples
CUse scipy.stats.chisquare to test, then plot a line plot of sample means
DUse scipy.stats.pearsonr to test, then plot a bar chart of correlation coefficients
Attempts:
2 left
💡 Hint
The Kolmogorov-Smirnov test compares distributions; histograms show distributions visually.

Practice

(1/5)
1. What is the main purpose of using SciPy together with Matplotlib in data science?
easy
A. To write text documents automatically
B. To create websites with interactive buttons
C. To store large amounts of data in databases
D. To perform mathematical calculations and then visualize the results

Solution

  1. Step 1: Understand SciPy's role

    SciPy is used for math tasks like integration, optimization, and fitting data.
  2. Step 2: Understand Matplotlib's role

    Matplotlib is used to create visual plots to show data and results clearly.
  3. Final Answer:

    To perform mathematical calculations and then visualize the results -> Option D
  4. Quick Check:

    SciPy + Matplotlib = Math + Visualization [OK]
Hint: SciPy does math, Matplotlib draws pictures [OK]
Common Mistakes:
  • Confusing SciPy with web development tools
  • Thinking Matplotlib stores data
  • Assuming SciPy creates visual plots
2. Which of the following is the correct way to import SciPy's integrate module and Matplotlib's pyplot for plotting?
easy
A. import scipy.integrate as integrate import matplotlib.pyplot as plt
B. import scipy.plot as sp import matplotlib as mpl
C. from scipy import plot import matplotlib.pyplot
D. import scipy.integrate as sp import matplotlib.pyplot as matplotlib

Solution

  1. Step 1: Check SciPy import syntax

    The correct way is to import the integrate module as 'integrate' for clarity.
  2. Step 2: Check Matplotlib import syntax

    Matplotlib's pyplot is commonly imported as 'plt' for easy plotting commands.
  3. Final Answer:

    import scipy.integrate as integrate import matplotlib.pyplot as plt -> Option A
  4. Quick Check:

    Standard imports use 'as integrate' and 'as plt' [OK]
Hint: Use 'as integrate' and 'as plt' for clear code [OK]
Common Mistakes:
  • Using wrong module names like scipy.plot
  • Not aliasing pyplot as plt
  • Importing entire matplotlib instead of pyplot
3. What will the following code display?
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import quad

def f(x):
    return np.sin(x)

result, error = quad(f, 0, np.pi)
plt.plot([0, np.pi], [0, result])
plt.title(f"Integral result: {result:.2f}")
plt.show()
medium
A. A line plot from 0 to π with y-values 0 to approximately 2 showing the integral result
B. A scatter plot of sine values between 0 and π
C. A bar chart showing the error value of the integral
D. An empty plot with no lines or points

Solution

  1. Step 1: Understand the integral calculation

    The code calculates the integral of sin(x) from 0 to π, which equals 2.
  2. Step 2: Understand the plot command

    It plots a line from (0,0) to (π, result), so from 0 to π on x-axis and 0 to ~2 on y-axis.
  3. Final Answer:

    A line plot from 0 to π with y-values 0 to approximately 2 showing the integral result -> Option A
  4. Quick Check:

    Integral of sin(x) 0 to π = 2, line plot shows this [OK]
Hint: Integral of sin(x) from 0 to π is 2, plot line shows it [OK]
Common Mistakes:
  • Thinking the plot shows sine wave points
  • Confusing scatter plot with line plot
  • Ignoring the integral result in the plot
4. The following code is intended to plot the cumulative integral of cos(x) from 0 to 2π, but it raises an error. What is the error and how to fix it?
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import cumtrapz

x = np.linspace(0, 2*np.pi, 100)
y = np.cos(x)

integral = cumtrapz(y, x)
plt.plot(x, integral)
plt.show()
medium
A. Error: plt.plot cannot plot arrays; fix by converting to list
B. Error: cumtrapz returns array shorter by 1; fix by plotting plt.plot(x[1:], integral)
C. Error: cumtrapz needs y first then x; fix by swapping arguments
D. Error: np.cos requires integer input; fix by converting x to int

Solution

  1. Step 1: Identify cumtrapz output length

    cumtrapz returns an array with length one less than input arrays.
  2. Step 2: Fix plotting mismatch

    Plot x[1:] with integral to match array sizes and avoid error.
  3. Final Answer:

    Error: cumtrapz returns array shorter by 1; fix by plotting plt.plot(x[1:], integral) -> Option B
  4. Quick Check:

    cumtrapz output length = input length - 1 [OK]
Hint: cumtrapz output shorter by 1, plot with x[1:] [OK]
Common Mistakes:
  • Plotting full x with shorter integral array
  • Trying to convert floats to int unnecessarily
  • Swapping arguments of cumtrapz incorrectly
5. You want to fit a Gaussian curve to noisy data points and then plot both the data and the fitted curve. Which approach correctly uses SciPy and Matplotlib together?
hard
A. Use matplotlib.pyplot.scatter to fit the curve, then plot with scipy.optimize.curve_fit
B. Use scipy.integrate.quad to fit the curve, then plot with matplotlib.pyplot.bar
C. Use scipy.optimize.curve_fit to find parameters, then plot data points and fitted curve with matplotlib.pyplot
D. Use numpy.polyfit to fit the curve, then plot with scipy.integrate.cumtrapz

Solution

  1. Step 1: Choose fitting method

    scipy.optimize.curve_fit is designed to fit functions like Gaussian to data.
  2. Step 2: Plot data and fit

    Use matplotlib.pyplot to plot original data points and the smooth fitted curve.
  3. Final Answer:

    Use scipy.optimize.curve_fit to find parameters, then plot data points and fitted curve with matplotlib.pyplot -> Option C
  4. Quick Check:

    curve_fit fits, pyplot plots data and fit [OK]
Hint: curve_fit fits data, pyplot plots results [OK]
Common Mistakes:
  • Using integration functions for fitting
  • Mixing plotting and fitting functions incorrectly
  • Using bar plots for continuous curve visualization